exception catch
(1) Syntax format:
try{
Code where exceptions may occur during the writing process;
}
catch(exception type reference variable name) {
Write the processing code for the exception class;
}
... (here means there may be multiple catch es)
finally{
Write code that is executed regardless of whether an exception occurs;
}
Precautions:
a. When you need to write multiple catch branches, remember to put the small type in front of the big type
b. It can also be written directly as:
catch(Exception e){}
c. finally is usually used for aftercare, such as: closing open files, etc.
(2) Exception catch case
FileInputStream example (subsequent IO streams will be involved, subsequent updates)
Detective exceptions---solution: catch exceptions
FileInputStream fis=new FileInputStream("d:/a.txt"); fis.close();
After writing the above code, it will display: Unhandled exception type FileNotFoundException
Use surround with try/catch to catch exceptions
Code after capture: (remember to assign the initial value null to the fis object, otherwise it will prompt: The local variable fis may not have been initialized; the variable has not been assigned an initial value)
FileInputStream fis=null; try { fis = new FileInputStream("d:/a.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
You can simply add output printing to observe the execution flow of the code in various situations, as shown in the following code:
// Detective exceptions---solution: catch exceptions FileInputStream fis = null; try { System.out.println("1"); //When an exception occurs during program execution, go straight to the catch branch for processing fis = new FileInputStream("d:/a.txt"); System.out.println("2"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("3"); e.printStackTrace(); System.out.println("4"); } try { System.out.println("5"); fis.close(); System.out.println("6"); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("7"); e.printStackTrace(); System.out.println("8"); }catch (NullPointerException e) { e.printStackTrace(); } System.out.println("The most affectionate interdependence in the world is you try I am here catch,No matter what kind of temper you lose, I will silently endure and deal with it quietly, and then I will look forward to our fianlly!"); } //When no exception occurs during program execution, the execution flow is: 1 2 5 6 in the world... //When an exception occurs during program execution, the execution flow is: 1 3 4 5 Null pointer exception, resulting in the program not being executed //Execution process when an exception occurs during program execution and the null pointer exception is handled manually: 1 3 4 5 in the world....
operation result:
1 3 java.io.FileNotFoundException: d:\a.txt (The system can not find the file specified.) 4 5 at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.io.FileInputStream.<init>(FileInputStream.java:93) at day03_Exception.ExceptionText.main(ExceptionText.java:14) java.lang.NullPointerException at day03_Exception.ExceptionText.main(ExceptionText.java:25) The most affectionate interdependence in the world is you try I am here catch,No matter what kind of temper you lose, I will silently endure and deal with it quietly, and then I will look forward to our fianlly!
The difference between manually handling exceptions and not handling them: whether the code can continue to execute.
(3)finally
When the exception is not handled manually, when an exception occurs, it will be automatically handed over to the JAVA virtual machine for execution, an error message will be printed, and the execution of subsequent code will be terminated.
Case code:
try { int ia=10; int ib=0; System.out.println(ia/ib); } catch (ArithmeticException e) { e.printStackTrace(); String str1=null; System.out.println(str1.length()); }finally { System.out.println("execute me whether or not an exception occurs~");//still execute } System.out.println("over!");//not implemented
operation result:
java.lang.ArithmeticException: / by zero execute me whether or not an exception occurs~ at day03_Exception.ExceptionFinallyText.main(ExceptionFinallyText.java:8) Exception in thread "main" java.lang.NullPointerException at day03_Exception.ExceptionFinallyText.main(ExceptionFinallyText.java:12)
Written test sites that may be involved: finally, the previous return value will be overwritten. code show as below:
package day03_Exception; import org.omg.CORBA.PUBLIC_MEMBER; public class ExceptionFinallyText { public static int test() { try { int[]arr=new int[5]; System.out.println(arr[5]); return 0; } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); return 1; }finally { return 2; } } public static void main(String[] args) { try { int ia = 10; int ib = 0; System.out.println(ia / ib); } catch (ArithmeticException e) { e.printStackTrace(); // String str1 = null; // System.out.println(str1.length()); } finally { System.out.println("execute me whether or not an exception occurs~");// still execute } System.out.println("over!");// not implemented System.out.println("==================="); int test=test(); System.out.println("test="+test); } }
Running result: (you can see that the final output result is test=2, which overwrites the 1 of the previous return 1)
execute me whether or not an exception occurs~ over! =================== java.lang.ArithmeticException: / by zero test=2 at day03_Exception.ExceptionFinallyText.main(ExceptionFinallyText.java:24) java.lang.ArrayIndexOutOfBoundsException: 5 at day03_Exception.ExceptionFinallyText.test(ExceptionFinallyText.java:9) at day03_Exception.ExceptionFinallyText.main(ExceptionFinallyText.java:35)
exception thrown
(1) Concept
In some cases, when some exceptions cannot be handled or are inconvenient to handle, the exception can be transferred to the caller of the method. This method is called exception throwing. When an exception occurs in the execution of the method, the bottom layer generates an exception. The class is thrown, and the code following the exception code will not be executed.
Syntax format:
Access rights Return value type Method name (formal parameter list) throws Exception type 1, Exception type 2.....{Method body;}
like:
public void show() throws IOException{
}
Code case:
public class ExceptionThrowTest { public static void show() throws IOException { FileInputStream fis =new FileInputStream("d:/a.txt"); System.out.println("See if the execution continues down after an exception is thrown"); fis.close(); } public static void main(String[] args) { try { show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
operation result:
java.io.FileNotFoundException: d:\a.txt (The system can not find the file specified.) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.io.FileInputStream.<init>(FileInputStream.java:93) at day03_Exception.ExceptionThrowTest.show(ExceptionThrowTest.java:9) at day03_Exception.ExceptionThrowTest.main(ExceptionThrowTest.java:16)
This shows that the output line is not executed! ! !
It is recommended not to throw exceptions in the main method, because the burden of the JAVA virtual machine itself is very heavy, so don't put any more burden on it~~~
The principle of method overriding:
1. The method name is required to be the same, the parameter list is the same, and the return value type is the same. Since jdk1.5, the return subclass type is supported;
2. The access authority of the required method cannot be smaller, and can be the same or larger;
3. The method is required not to throw a larger exception
Notice:
A method overridden by a subclass cannot throw a larger exception, cannot throw an exception of a different level, but can throw the same exception, a smaller exception, and no exception.
Experience sharing:
1. If the overridden method in the parent class does not throw an exception, the overridden method in the subclass can only handle exception capture.
2. If a method internally calls several other methods in a progressive manner, it is recommended that these methods can use the thrown method to process to the last layer for capture processing.
Sample code:
The first is that the ExceptionMethod class looks like this:
public class ExceptionMethod { public void show()throws IOException{} }
The second is the subclass SubExceptionMethod class that inherits the ExceptionMethod class. The code of the subclass SubExceptionMethod is as follows:
public class SubExceptionMethod extends ExceptionMethod{ /* * Methods overridden by subclasses can throw the same exceptions as in parent class methods */ @Override //public void show()throws IOException{} //Methods overridden by subclasses can throw smaller exceptions, FileNotFoundException is a subclass of IOException //public void show()throws FileNotFoundException{} //public void show() {}//Subclasses can not throw exceptions public void show()throws ClassNotFoundException{}//Cannot throw exceptions of different levels public void show()throws Exception{}//Cannot throw a higher exception }
Through the above simple example, the three principles of method overriding can be verified. I'll be here today~~~ Open the implementation of custom exception classes tomorrow.