1. Inheritance structure of classes
All exception objects in Java are instances of a subclass of the Throwable class
Exception contains two branches, due to program errors caused by the exception belongs to RuntimeException, such as array subscript out of bounds, null pointers and so on. Exceptions for non-program itself problems are other exceptions, such as IO-induced exceptions.
All exceptions that derive from the error class or the RuntimeException class belong to the check exception, and all other exceptions belong to the checked exception, we only need to specify the exception handler for the regular exception, in other words, we only need to write a catch statement for the checked exception.
2. Declaration of method exceptions
Method should declare all possible exceptions at its header
String ReadData (Scanner in)throw eofexception{ //...}
3. Exception throws
String ReadData (Scanner in) thethrow eofexception{ while() {if () { thrownew eofexception ();}}}
4. Capture of methods
If the A method invokes the B method that declares the throw exception, either handle the exception in the A method or continue to throw the exception.
Try { //... }catch(FileNotFoundException e) { //... }catch(IOException e) { //... }finally{ file.close ();}
5.finally clause a try statement with a resource
In the above code, we use the finally clause to do the file close operation, which is a common requirement in the actual development process, because the statements in the FINALLY clause are executed regardless of whether there is an exception in the TRY statement block, so the file is closed in the finally clause, Streaming shutdown and database shutdown are a good choice to avoid writing duplicate code inside and outside of a try statement block.
Another good option is to use a try statement with a resource, because a try with a resource automatically calls Res.close () when exiting (regardless of normal exit or exception), so we can still do the file close without writing the finally statement.
Try New Scanner (new Fileinputstrem ("/usr/tmp/test")){ while(In.hasnext ()) ) System.out.println (In.next ());}
Brief introduction to Java exception mechanism