We know that try is responsible for typing out codes that may produce exceptions; catch is responsible for handling possible exceptions in try, such as recording error logs to enable business to run normally; finally responsible for aftermath work such as resource release, and code that must be executed regardless of whether there are or not is generally placed in finally. If catch and finally also experience exceptions, what will be the effect?
try { // java.lang.ArithmeticException int a = 1 / 0; } catch (Exception e) { System.out.println("catch"); // java.lang.NullPointerException String value = null; System.out.println(value.length()); } finally { System.out.println("finally"); // java.lang.ArrayIndexOutOfBoundsException int[] array = {1, 2, 3}; System.out.println(array[6]); }The final execution result of this code is: an ArrayIndexOutOfBoundsException will be thrown. An exception occurs in the code in the try, and the corresponding catch will be executed;
If an exception occurs when catch, it will be executed finally; if finally there is an exception, it will be directly thrown to the JVM because it is not processed. If not used here
Finally block, a NullPointerException will be thrown.
This means that exceptions that appear in catch and finally will be thrown directly. If we do not process it, an error will be generated at runtime. This reminds us that if catch and finally exceptions may also occur, then try-catch must be processed again.
Some notable things (must read) in the above article "try-catch-finally" are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.