Java syntax Summary-exception
An old saying in software development is that 80% of Jobs use 20% of their time. 80% refers to the efforts made to check and handle errors. In many languages, programming code that checks and handles errors is tedious and lengthy. One of the reasons is that their error handling methods are not part of the language. Despite this, error detection and processing are still the most important part of any robust application.
Java provides a good mechanism to eliminate the arbitrary factors in the error handling process in the form of mandatory rules: exception handling. Its advantage is that it can easily detect errors without writing special code to check the return value. In addition, it allows us to clearly separate the exception handling code from the exception generation code, and the code becomes more organized. Exception Handling is also the only formal error reporting mechanism in Java.
Part 1 exception
1. Throw an exception. All standard exception classes have two constructors: one is the default constructor and the other is a constructor with parameters to put relevant information into the exception object.
Throw new nullpointerexception ();
Throw new nullpointerexception ("t = NULL ");
2. If one or more catch blocks exist, they must be followed by the try block, and these catch blocks must be followed by each other and cannot have any other code. C ++ does not have such restrictions. Therefore, if the exception handling in C ++ is not handled properly, it will be messy and thrown to the hacker.
3. Use the try block to include code that may cause exceptions. The advantage of doing so is that you only need to write the code that handles a specified exception once. Students who haven't finished their homework will go to the corridor to send a penalty. This is in line with the way we handle the problem, so we don't have to tell them one by one.
4. No matter whether an exception is thrown or not, the Finally block encapsulated code can always be executed at a certain point after the try block.
Example:
Try {
Return;
}
Finally {
System. Out. Print ("you can't jump out of my hand! ");
}
You cannot even use the return statement in the try block to skip it! The finally output statement is still executed! Don't escape from my palm!
5. Catch blocks and finally blocks are optional. You can only use try. But is this interesting?
6. shirk responsibility. Java allows you to shirk responsibility, and there is no need to write catch clauses for every possible exception from the corresponding try block. Many methods in the Java2 class library throw an exception, that is, the exception handling permission is handed over to our users. After all, Java does not know if your bicycle is stolen, and you will report the case to the police, and you will still feel unlucky or steal others' bicycles. We need the freedom to handle exceptions.
7. Call Stack. The call stack is the method chain in which the program executes to access the current method. The last method called is located at the top of the stack. It is executed first and then popped up. The first method is located at the bottom, that is, the main function. Using the printstacktrace () method in the catch clause to call stack information is a common method for locating exceptions. Printstacktrace () inherits from throwable.
8. propagation of exceptions. In method A, if an exception is not processed, it is automatically thrown to Method B that calls method. If Method B does not handle this exception, it will continue to be thrown up until the main method. If main does not care about it, the exception will cause JVM to stop and the program will be aborted. You have been beaten by your classmates. Tell the teacher first. If the teacher ignores you, you will tell the director of the Teaching director. No matter what the director is, you can only tell the principal that the principal does not care! No bigger than him, so you collapsed and your studies stopped ...... The following procedure records the tragic drop-out history:
Class exceptiondemo {
Static void student () throws exception {
Teacher ();
}
Static void teacher () throws exception {
Schoolmaster ();
}
Static void schoolmaster () throws exception {
Throw new exception ();
}
Public static void main (string [] ARGs ){
Try {
Student ();
}
Catch (exception e ){
E. printstacktrace ();
}
}
}
The output result is:
Java. Lang. Exception
At exceptiondemo. schoolmaster (exceptiondemo. Java: 9)
At exceptiondemo. Teacher (exceptiondemo. Java: 6)
At exceptiondemo. Student (exceptiondemo. Java: 3)
At exceptiondemo. Main (exceptiondemo. Java: 13)
We can see that the function call stack is crying at the first level ......
9. Exception hierarchy and error.
Object
Throwable
Error exception
Throwable inherits from object, error and exception inherit from throwable. Error is special. It corresponds to the irresistible external force that we often call. There is always one piece in the contract of the Housing Agency. In case of irresistible force, the contract is terminated and the deposit of Party B is returned. I am anxious to ask: What does an irresistible external force mean? The intermediary replied: for example, war, comet hitting the Earth, etc. For Java, error refers to JVM memory depletion and other special situations that are not caused by program errors or other things. Generally, the program cannot be recovered from the error, so you can watch the program crash without blaming yourself. Strictly speaking, error is not an exception because it does not inherit from exception.
10. Who's wrong? Generally, exceptions are not the fault of our programmers, nor are they a defect in programming. For example, when reading an important file, the file is accidentally deleted by the user; while the network is on, the network cable is bitten by the user's pet. To ensure program robustness, we try to consider and handle possible exceptions, but we cannot exhaust them.
11. Exception capture. The catch clause parameter is an object of some type exception. If the thrown exception is a subclass of this parameter, this exception will be caught by it. That is to say, the thrown exception does not precisely find the most matched catch clause, as long as it is the immediate upper layer of Its Inheritance structure.
According to this logic, can catch (exception e) catch all exceptions? In fact, it does. However, generally, this one-stop exception handling is not recommended. In this way, the specific exception information is lost, and the corresponding Exception Handling Code cannot be written for a specific exception, thus the significance of exception handling is lost. From a philosophical point of view, specific problems should be analyzed. The universal medicine that can cure all diseases is generally ineffective health care products.
Why is Java designed here? Because there is another mechanism, please refer to the next decomposition.
12. Capture exceptions. When an exception is thrown, Java tries to find a catch clause that can capture it. If not, it will spread down the stack. This process is abnormal matching. Java rules: the most specific exception handling program must always be placed before the more common exception handling program. This rule is no more reasonable. Imagine if we put catch (exception e) at the top, wouldn't the following catch clause be permanently executable? If you have to put more common exception handling at the front, sorry, you can't compile it! Although the compiler does not report the following error: "It is so stupid to do like that !"......
13. capture or declare rules. If an exception is thrown in a method, you have two options: capture all exceptions with the catch clause, or declare the exception to be thrown in the method, otherwise the compiler won't let you succeed.
Solution 1: handle exceptions
Void ex (){
Try {
Throw new exception ();
} Catch (exception e ){
E. printstacktrace ();
}
}
Solution 2: Throw
Void ex () throws exception {
Throw new exception ();
}
By comparing the number of lines, it is easy to shirk responsibility in the Code world. How much life philosophy does a throws keyword contain ...... In real life, we have many roles, including children, parents, students, teachers, bosses, and employees ...... Each person occupies several items. But can you fulfill all your responsibilities? According to the ancient filial piety, when the parents are still living, they cannot go far. There are contradictions between various responsibilities.
However, this rule has a special case. A subclass inherited from the Exception name runtimeexception, that is, a runtime exception, is not restricted by the preceding rules. The following code can be fully compiled, but an exception will be thrown during runtime after the call.
Void ex (){
Throw new runtimeexception ();
}
14. Keyword throw and thrwos. Throw throws an exception in the method body, followed by a specific exception object. Throws is used behind the brackets in the method parameter list to declare the type of exception thrown by this method, followed by an exception class.
15. Non-check exceptions. Runtimeexception, error, and their subclasses are non-check exceptions and do not require defining or processing non-check exceptions. There are many methods in the Java2 class library that throw check exceptions. Therefore, exception handling programs are often written to handle exceptions that are not produced by the methods you write. This mechanism forces developers to handle errors, making Java programs more robust and secure.
16. custom exception type. I think the existing exception cannot describe the exception you want to throw. OK! Java allows you to customize the exception type. You only need to inherit the exception or its subclass, and then replace it with a personal name.
Class notenoughmoney extends exception {
Public notenoughmoney (){}
Public notenoughmoney (string MSG) {super (MSG );}
}
I hope you will not throw similar exceptions in your life.
17. Throw an exception again. A boring topic, purely syntactic research, has little practical significance. If an exception is caught in a catch clause, the method in which the catch clause is located must declare the exception.
Void ex () throws exception {
Try {
Throw new exception ();
}
Catch (exception MEX ){
Throw me;
}
}
18. Efficiency of the exception handling mechanism. To be supplemented ......
19. Terminate and recover the model. In theory, there are two types of exception handling models:
I. Terminate the model. The error is critical and irretrievable. It makes no sense to execute it again. It can only be aborted. "Romeo, let's break up !" "Okay, Juliette !"
2. Restore the model. After error correction, try again to call the method of the original problem. "Romeo, let's break up !" "Juliette, I am wrong! Forgive me again !" "Okay, forgive you for the last time !"
Obviously, we prefer to restore the model, but in practice, this mode is not easy to implement and maintain.
Example: The user inputs invalid characters and processes them in two modes.
I. Terminate the model. The error message is output. Once the user's hands shake your eyes, your code will crash.
Double number;
String snumber = "";
Try {
Bufferedreader BF = new bufferedreader (New inputstreamreader (system. In ));
Snumber = BF. Readline ();
Number = double. parsedouble (snumber );
} Catch (ioexception IOE ){
System. Err. println ("Some ioexception ");
} Catch (numberformatexception NFE ){
System. Err. println (snumber + "is not a legal number! ");
}
// System. Out. println (number );
2. Restore the model. Look down! If you do not enter the correct data type, do not leave!
Double number = 0;
String snumber = "";
While (true ){
Try {
Bufferedreader BF = new bufferedreader (New inputstreamreader (system. In ));
Snumber = BF. Readline ();
Number = double. parsedouble (snumber );
Break; // if the code can be executed to this line, it indicates that no exception is thrown.
} Catch (ioexception IOE ){
System. Err. println ("Some ioexception ");
} Catch (numberformatexception NFE ){
System. Err. println (snumber + "is not a legal number! ");
}
}
System. Out. println (number );
This code will not be used until the user enters the correct information. This is a simple implementation of the recovery model, which is quite intuitive and I like it very much!
20. Scope and visibility of variables in try, catch, and finally.
Variables defined in the try block cannot be accessed in the catch or finally block and are invisible outside the entire Exception Handling statement.
One more initialization: The last sentence in the first example is commented out. The number is initialized by user input at runtime, but it is not initialized at Compilation Time. The compiler will complain.
21. Output exception information. After an exception is captured, we usually output relevant information to make the exception clearer.
Catch (exception MEX ){
System. Err. println ("caught a exception! ");
}
It is better to use the standard error stream system. Err than system. Out. Because system. out may be redirected, and system. Err will not.
22. I will add more advanced topics, but my stomach throws a hungry exception. I have to catch and then call the Eat () method to supplement energy. The squid covered last night is delicious ......