Why do I need an exception?
In the past, when writing data structures in C, there is always such a worry: for example, the pop function of the stack, in addition to the function body to complete the operation of the stack, but also to use a return value, indicating whether the stack operation is successful.
However, in order to return the value of the stack to the caller, it is necessary to use the return statement. But return is occupied by the function state value, so can only use pointers, this must give the POP function to add a pointer parameter, it is inconvenient to use.
Java built-in exception mechanism, the function can be executed, if something unexpected happens, the exception will occur, our program can handle these accidents by exception. This separates the function from the execution state of the function and writes the code more clearly.
Javainheritance structure and classification of exceptions
All exceptions in Java are Throwable subclasses, with 2 branches below: Error and exception.
Error does not need to be our control, when error occurs, you should blame Java itself. Java runtime, itself the system is out of the question, this is not your code problem. So we don't even have to worry about this branch of error. Error generally occurs infrequently.
Exception can also be divided into 2 categories: RuntimeException and non-runtimeexception exceptions.
When the RuntimeException exception occurs, it is certain that your code has a problem, specifically the logic of the code is a problem, not a grammatical problem, the syntax of the problem at compile time will prompt you.
For example, using a null pointer, array subscript out of bounds, infinite loop caused by the StackOverflow and so on. When these anomalies occur, you should try to modify your code instead of trying to capture them. These can be avoided.
Non-runtimeexception anomalies (dark blue marks in the figure), contrary to runtimeexception, they are programmers unavoidable, such as the implementation of an IO operation, the computer may not have disk capacity, or the user removed the IO device. When the data is downloaded, the network is disconnected ...
Non-runtimeexception exceptions are the exception branches that we are most concerned about in Java exception handling.
In addition: An obvious difference between runtimeexception and non-runtimeexception exceptions is that if you use Eclipse, the compiler will alert you and force you to handle
Non- runtimeexception exception, for runtimeexception exceptions, the compiler will not remind you to handle them.
Uimanager.setlookandfeel is the way the UI senses are set in swing, which throws: Non-runtimeexception exceptions such as ClassNotFoundException
Stringindexoutofboundsexception is a runtimeexception,eclipse won't remind you.
what happens after an exception occurs
The first thing to be clear is that the exception is generated within the method, because the method is used to manipulate the data, the operation data can be abnormal.
We also need to understand the function call stack: The function of the call when the form of a stack management, the level of calls, sequentially into the stack.
When an exception occurs on a layer, the method does not continue to execute. Instead, backtrack down to find the exception handler.
Once the exception handler is found, the exception is disposed on that layer, and finally, the layer is executed later.
If there is no exception handler that goes back to the bottom of the stack, the thread terminates.
Let's look at a small example:
Public Static voidFoo1 ()throwsexception{Foo2 ();} Private Static voidFoo2 ()throwsexception{Throw NewException (); } Public Static voidMain (String []args) {Try{foo1 (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }
We can print the stack information of the exception using the Printstacktrace () method of the exception.
handling Exceptions in code
The main purpose is to use try...catch....finally statements.
1, catch (Xxxexception e), when an exception occurs, the catch matches to Xxxexception, the runtime system assigns the generated exception object to the variable E. This way, the exception's detail exception can be obtained by analyzing the exception variable E.
2. Finally, it is mainly used in the finishing work of the abnormal processor. Close some resources. For example, a text read a piece, regardless of the successful read, or read the exception occurred, and finally to close the file stream, this time to use finally.
3. The order of catch statements should be from specific exceptions to broad exceptions, from special exceptions to general exceptions.
Try { file.read (); } Catch (eofexception e) { //eofexception is a subclass of IOException }catch (IOException e) { //ioexception is a subclass of Exception }catch(Exception e) { }
4. If a subclass makes a method that throws an exception in the parent class, this method of the subclass should throw the same exception as the parent class, or it is a subclass exception, or not throw an exception, but in a controlled range of the parent class exception. Think of it, if you don't follow this rule, then polymorphism can't be achieved.
5, if a method has an exception, and does not handle it, it will break execution, there will be no return value.
6. If the return statement is written in a try block, the finally (if any) will be executed before return.
Throw an exception in the method
If an exception is thrown in a method and the method itself is not processed, let the caller decide what to do with it. Then, it must use the throws statement to declare all the exception types it might throw in the function header.
The purpose of a declaration is to inform the caller: I might throw an exception and you need to be prepared.
Here is the function header of Setlookandfeel in the Uimanager class in swing, which declares the exception it throws.
Public Static void Setlookandfeel (String className)throws classnotfoundexception, Instantiationexception, illegalaccessexception, unsupportedlookandfeelexception { //...}
Proactively throwing exceptions
Use the throw statement followed by an exception object. Throws an exception object.
The following is a custom function that capitalizes the argument string.
Private throws exception{ if(s==null) thrownew Exception (" Paramter is null "); Else if (S.equals ("")) Throw New Exception ("Empty String"); Else return s.touppercase (); }
Handling exceptions, but throwing exceptions
Sometimes, a method needs to filter the exception that occurs, or to hide some exceptions from the caller and only throw exceptions that the caller can understand, then it is necessary to capture the exception and then throw it appropriately.
Example function: Print the first character of a string
Private void Printfirst (String s) { try { System.out.println (S.charat (0)); } Catch (nullpointerexception e) { throw e; //Catch an exception and throw it to the caller } Catch (stringindexoutofboundsexception e) { //do nothing. Handle it yourself and do not advertise the caller. } }
to define your own exceptions
Common methods of exceptions
E.getmessage () Print exception details
E.printstacktrace () print exception tracking stack
E.localized description of the Getlocalizedmessage () exception
class extends exception{ public myexception () { Super(); } Public myexception (String msg) { super(msg); } }
finally
When I wrote this essay, I struggled to write an example of a representative anomaly, but I couldn't think of it. Usually write code abnormal swarming, really want to abnormal code, still really can't think out, alas, or write code to go.
Java Exception Handling