Java Exception Handling
The basic idea of Java is "" -- Thinking in Java.
Exception Handling in Java is an error reporting mechanism in the compilation phase, which is enforced by the compiler. But I still need to understand
Yes: no errors can be found during compilation, and the remaining problems must be solved during runtime.
Simply put, exception handling aims to make your program more reliable with a small amount of code.
Try, catch, and finally encounter return
I will not mention how to use exceptions in Java. I am interested in the try, catch, and finally blocks.
The execution of the return Statement and the return value (there are always written and interview questions ).
The first thing to note is that it is wrong to return the result and terminate the result when the return statement is executed by the method. The exception is the exception system of Java.
Let's look at the example program below:
package com.al;public class ExceptionTest{ @SuppressWarnings("finally")public String test(){ String returnStr ="start"; try {System.out.println("start String:"+returnStr);returnStr="try innner";throw new Exception("inner Exception");} catch (Exception e) {returnStr ="catch inner";return returnStr;}finally{returnStr = "finally";System.out.println("inner finally:"+returnStr);return returnStr;} } public static void main(String[] args) {ExceptionTest exceptionTest = new ExceptionTest();try { String test=exceptionTest.test();Thread.sleep(300);System.out.println("returnString:"+test);} catch (InterruptedException e) {// TODO: handle exception}}}
Output result:
Start String: start
Inner finally: finally
ReturnString: finally
Understanding the following rules can solve the return problem.