1, Try-catch
E.printstacktrace (); Will print out the method's call traces, in this case, will print out the exception starts at the 16th line of testexception, so that it is easy to locate and analyze where the exception
2. Catch with the parent class of the exception class
FileNotFoundException is a subclass of exception, and using exception can catch FileNotFoundException
3, multi-exception capture Method 1
Catch (FileNotFoundException e) { System. out. println ("D:/lol.exe does not exist ") ; Catch (ParseException e) { System. out. println (" date format parsing error "); E.printstacktrace ();}
Multiple anomaly Capture Method 2: Another approach is to put multiple exceptions in a catch to uniformly capture
Catch (FileNotFoundException | parseexception e) {}
// This approach is supported from JDK7, and the benefit is that the captured code is more compact, and the disadvantage is that once an exception occurs, it is not possible to determine what kind of exception it is, and the specific type of exception needs to be judged by instanceof if (e instanceof filenotfoundexception) System. out. println ("D:/lol.exe does not exist "); if (e instanceof parseexception) System. out. println (" date format parsing error ");
4. Finally: The code in finally will be executed regardless of whether an exception occurs
5. Throw
Exception handling is required in METHOD2
But Method2 not to deal with it, but to throw it out through throws.
Then METHOD1 will receive the exception. There are two ways to deal with it, either a try catch or a throw away.
Method1 Select local Try Catch live once try catch, it is equivalent to digest this exception, the main method when calling Method1, do not need to do exception handling
Package exception; import java.io.file;import Java.io.fileinputstream;import java.io.FileNotFoundException; Public classTestException { Public Static voidMain (string[] args) {method1 (); } Private Static voidmethod1 () {Try{method2 (); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Private Static voidMethod2 () throws FileNotFoundException {File F=NewFile ("D:/lol.exe"); System. out. println ("trying to open D:/lol.exe"); NewFileInputStream (f); System. out. println ("successfully opened"); }}
Java Exception Base Collation