We can also use the try...catch...finally statement to handle exceptions. When the program executes to the error code, the system will throw an exception object, and the program will enter the catch block to match one by one. If the match is successful, the program will execute the catch code. If If the matching fails, the program is returned to the Java virtual machine for processing.
The format of the try...catch...finally statement is as follows: try{//Contains statements that may cause exceptions}catch (exception class name exception object){//Exception handling code}finally{//Code that must be executed}
Things to note:
1) Try to keep the try block code as small as possible.
2) Once an exception occurs in the try block code, no matter how many lines of code follow the try block, it will not be executed.
3) The exception parameter matching in the catch block also satisfies the polymorphic Exception e = new ArithmeticException(/by zero);
4) There can only be one try block , and there can be multiple catch blocks . Try can be combined with catch, try can be combined with finally, and try can be combined with catch and finally.
5) Generally, Exception is used as the parameter type of catch at the end of the exception handling format.
6) Execption as a parent class exception parameter can only appear at the end of the exception, first the subclass and then the parent class.
7) The finally modified code block will definitely be executed unless the program exits abnormally or the system exit method is called before execution reaches finally.
8) In the try statement, when the return statement is executed, the result to be returned is ready. At this time, the program switches to finally execution. Before transferring, try first stores the result to be returned in a local variable different from x. After executing finally, the returned result is taken out. Therefore, even if the variable x is changed in finally, it will not If it affects the return result, the stack should be used to save the return value.