Java – try, catch and finally blocks
•
Java
public class D {
public class D { void myMethod() { try { throw new IllegalArgumentException(); } catch (NullPointerException npex) { System.out.println("NullPointerException thrown "); } catch (Exception ex) { System.out.println("Exception thrown "); } finally { System.out.println("Done with exceptions "); } System.out.println("myMethod is done"); } public static void main(String args[]) { D d = new D(); d.myMethod(); }
}
I don't understand why "mymethod complete" is printed out An exception is thrown, so it assumes that a matching catch is found and the finally block is executed, but it continues on the mymethod method method and prints that the mymethod is completed, which is not part of the finally block Why?
Solution
This is how try catch finally works Because you caught an exception, it is considered handled and execution continues normally
If you don't catch it or throw it again, "mymethod is finished" won't be printed, and the exception will pop up in the stack until it is caught by others
Note that finally blocks are always executed, exception or no
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码