YouTip LogoYouTip

Exception Finally

# Java Example - Usage of Finally\n\n[![Image 3: Java Example](#) Java Example](#)\n\nThe `finally` keyword in Java is generally used together with `try`. After the program enters the `try` block, the content of the `finally` block will always be executed, regardless of whether the program terminates abnormally due to an exception or returns in some other way.\n\nThe following example demonstrates how to use `finally` to catch an exception (IllegalArgumentException) via `e.getMessage()`:\n\n## ExceptionDemo2.java File\n\n```java\npublic class ExceptionDemo2{\n public static void main(String[]argv){\n new ExceptionDemo2().doTheWork();\n }\n public void doTheWork(){\n Object o = null;\n for(int i=0; i<5; i++){\n try{\n o = makeObj(i);\n }catch(IllegalArgumentException e){\n System.err.println("Error: ("+ e.getMessage()+").");\n return;\n }finally{\n System.err.println("All have been executed.");\n if(o==null)\n System.exit(0);\n }\n System.out.println(o);\n }\n }\n public Object makeObj(int type)throws IllegalArgumentException{\n if(type == 1)\n throw new IllegalArgumentException("Not the specified type: " + type);\n return new Object();\n }\n}\n\nThe output of the above code is:\n\nAll have been executed.\njava.lang.Object@7852e922\nError: (Not the specified type:1).\nAll have been executed.\n\n[![Image 4: Java Example](#) Java Example](#)
← Net UrlNet Serverfile β†’