(all screenshots in the figure, as well as data notes, come from the power node, for self-study and use)
1. What is the exception?
First, abnormal simulation is "abnormal" events in the real world
Second, in java, exceptions are simulated by means of "classes"
Exception description under java.lang package
Third, classes can create objects
NullPointerException e = 0x1234; / / this is equivalent to the instantiation of a class. Instantiating an exception class becomes a real exception event
This object must be of type NullPointerException
This object represents the real abnormal event
NullPointerExceptions is a type of exception
"Robbery" is a kind of abnormality It's an unusual time for Zhang San to be robbed.
2. What is the effect of abnormal mechanism?
java language provides us with a perfect exception handling mechanism,
The function is to output detailed information for us after an exception occurs,
Through this information, the programmer can process the program and make it more robust
public class Test{ public static void main(String[] args){ int a = 5; int b = 0; int c = a/b; //There is no problem with the program syntax. The compilation can pass, but it does not conform to the mathematical rules and cannot be run System.out.println("hello"); // If the above exception is not handled, the following statement will not be executed, and the JVM will automatically exit the statement /*Exception in thread "main" java.lang.ArithmeticException: / by zero at Exception mechanism / test.Test01.main(Test01.java:8)*/ Abnormal feedback reported by the system //Essence: an arithmetic exception occurred during the execution of the program. The JVM created an object of type ArithmeticException for us. And this object contains detailed exception information, and the JVM outputs the information in this object to the console. } } //After we know the exceptions, we can handle them by changing the code public static void main(String[] args){ int a = 11; int b = 0; if(b!=0){ System.out.println(a+"/"+b+"="+a/b); }else { System.out.println("b Can not be 0"); //This is exception handling, which avoids the occurrence of exceptions } }
Exception inheritance structure chart
Throwable() all exception and error superclasses are inherited from it
Exception s are divided into compile exceptions and run-time exceptions
Compile time exceptions (there are many) and runtime exceptions are E
The difference between compile time exception and run time exception
All compile time exceptions require the programmer to handle them during the programming phase. If they are not handled, the compilation cannot pass. There are two ways to handle exceptions: catch and declare throw. Capture: try Catch... , declaration throw is to throw an exception at the position of the method declaration using the throws keyword,
High compile time exceptions
All subclasses of RuntimeException are run-time exceptions, which the programmer does not need to handle at the writing stage
The probability of operation is relatively low
There are two ways to handle exceptions: 1. Declaration throw: throws 2. Capture: try...catch The following program demonstrates the first way: declare a throw, and use the throws keyword to throw an exception up where the method is declared.
public class Test{ public static void main(String[] args) { //Thinking: how does the java compiler know that exceptions may occur during code execution //How does the java compiler know that this exception is more likely to occur? FileInputstream fis = new FileInputstream("c:/ab.txt") //In fact, when I check the definition of FileInputStream class in API document, I have the following code public FileInputStream (String name) throws FileNotFoundException this class is followed by throws when it is defined, and throws is followed by a FileNotFoundException exception, which inherits from the compilation exception. Therefore, to call this class, there must be an exception handling mechanism for, } } //The above program fails to compile /* Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException at exception mechanism / running exception.Tets.main(Tets.java:6) */
The following program demonstrates the first method of exception handling: declaration throwing, using the throws keyword to throw an exception upward at the position of the method declaration
Without throws, that is, without exception handling mechanism, compilation will fail. But with exception handling mechanism, compilation can pass. Statements before exceptions can run normally, but statements after problems cannot pass
public class Test{ //public static void main(String[] args) throws IOException //public static void main(String[] args) throws Exception public static void main(String[] args) throws FileNoFoundException{ FileInputStream fis = new FileInputStream("c:/ab.txt"); } }
Deep into throws
Throws stands for throwing up, for calling its method, and needs to be followed by exception handling class with throws
When an exception occurs, throws will be thrown up uniformly, but it will not be solved. If it is thrown on the Internet all the time, and it is not solved, the JVM will finally end the program
Exception through try catch... To solve
public class Test{ public static void main(String[] args) throws FileNotFoundException{ m1(); //Using throws to handle exceptions does not really handle exceptions but shirks responsibility. //Whoever calls it will be thrown to whoever. //If there is an exception in the m1 method above, because it is thrown up and given to the JVM, the JVM will exit the JVM when it encounters this exception, and the following code will not execute System.out.println(); } public static void m1() throws FileNotFoundException{ m2(); } public static void m2() throws FileNotFoundException{ // Because there are throws on the m3 method, the 'm2() calling it' also needs to follow the exception handling mechanism with throws m3(); } public static void m3() throws FileNotFoundException{ //Because FileInputStream has throws, it needs to use throws after m3 method new FileInputStream("c:/ab.txt"); //There is a FileInputStream but no processing mechanism, so if you write this directly, an error will be reported } } //This is the error message after the program //An exception of type FileNotFoundException occurred while the program was running JVM Created a FileNotFoundException Object of type. //This object carries the following information: //The JVM is responsible for printing the object's information to the console //And the JVM stops the program Exception in thread "main" java.io.FileNotFoundException: c:\ab.txt (The system cannot find the specified file.) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:213) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110) at Exception mechanism/Abnormal operation.Test.m3(Test.java:21) at Exception mechanism/Abnormal operation.Test.m2(Test.java:18) at Exception mechanism/Abnormal operation.Test.m1(Test.java:15) at Exception mechanism/Abnormal operation.Test.main(Test.java:8)
The second way to handle exceptions: catch try... Catch...
1.catch statement can write multiple statements quickly
2. However, from top to bottom catch, you must catch from small type exception to large type exception.
3.try... Catch... At most 1 catch statement block is executed in. Try after execution Catch... It's over.
As mentioned earlier, if there is an exception, the object will be created. In catch, the exception object capture is assigned to the variables in
Syntax: try{ Code with possible exception; }Catch (exception type variable) {/ / the memory address of the variable points to the object in the heap, which is the instantiation of "exception type" Code for handling exceptions; } Catch (exception type variable){ Handle exception code; } 1. The catch statement block can write multiple
public class ExceptionTest{ try{ FileInputStream fis = new FileInputStream("c:/ab.txt"); }catch(ArithmeticException e ) {//It's not good to write like this, because it's wrong to catch it. We want to catch the FileNotFoundException exception exception, but here we catch the math exception. So when we choose the exception to catch, we must first see which exception will appear in the code that may appear in the try, and then decide which exception to catch } //The following program can capture the same exception as possible through try{ FileInputStream fis = new FileInputStream("c:/ab.txt"); }catch(FileNotFoundException e ){ } try{ FileInputStream fis = new FileInputStream("c:/ab.txt"); fis.read(); //The read() method is a FileInputStream inherited from its parent class InputStream, while the InputStream throws method is IOException }catch(FileNotFoundException e ) { }catch(IOException e){ } //The following methods can also be compiled, but they may not be handled specifically try{ FileInputStream fis = new FileInputStream("c:/ab.txt"); fis.read(); } catch(IOException e){ } //Compilation failed, //catch can write multiple, but it must be captured from top to bottom, from small to large try{ FileInputStream fis = new FileInputStream("c:/ab.txt"); fis.read(); }catch( IOException e){ }catch(FileNotFoundException e){ } } //It should be noted that when there is a statement exception in try, the statement after try will not be executed after catching and processing, so it responds to the condition that the previous catch statements execute only one try{ FileInputStream fis = new FileInputStream("c:/ab.txt"); fis.read(); }catch( IOException e){ System.out.println("Error in read path"); }catch(FileNotFoundException e){ System.out.println("err!"); }
On the application of getMessage and printStackTrace methods
public class ExceptionTest{ public static void main(String[] args) { try{ FileInputStream fis = new FilesInputStream("c:/ab.txt"); //The JVM executed the following code for us // FileNotFoundException e = new FileNotFoundException("c:/ab.txt cannot find the specified file") //This will inherit the relationship, and the construction method will continue to upload to the getMessage method in Throwable //It's the JVM that assigns values for us and then transmits them online } catch(FileNotFoundException e){ //Print exception stack information //In general, this method is used to debug programs e.printStackTrace(); //If this method is not added, the following error information will not be printed, and the system will directly run downward without giving error information /* * java.io.FileNotFoundException: sd (The system cannot find the specified file. at * java.base/java.io.FileInputStream.open0(Native Method) at * java.base/java.io.FileInputStream.open(FileInputStream.java:213) at * java.base/java.io.FileInputStream.<init>(FileInputStream.java:155) at * java.base/java.io.FileInputStream.<init>(FileInputStream.java:110) at * Exception mechanism / running exception.Test01.main(Test01.java:9) */ //Another way String ms = e.getMessage(); //getMessage is inherited from throwable System.out.println(msg); //There will be the following error messages //sd (the system cannot find the specified file. ) } //After there is a specific processing method in catch, the following code will continue to execute System.out.println("ABC"); } }