如何使用 finally 块捕获 Java 中的异常
问题描述
如何使用 finally 块捕获异常?
解决方案
此示例显示如何使用 finally 块通过使用 e.getMessage() 捕获运行时异常(非法参数异常)。
public class ExceptionDemo2 { public static void main(String[] argv) { new ExceptionDemo2().doTheWork(); } public void doTheWork() { Object o = null; for (int i = 0; i < 5; i++) { try { o = makeObj(i); } catch (IllegalArgumentException e) { System.err.println("Error: ("+ e.getMessage()+")."); return; } finally { System.err.println("All done"); if (o == null) System.exit(0); } System.out.println(o); } } public Object makeObj(int type) throws IllegalArgumentException { if (type == 1)throw new IllegalArgumentException("Don't like type " + type); return new Object(); } }
结果
上述代码示例将产生以下结果。
All done java.lang.Object@1b90b39 Error: (Don't like type 1). All done
以下是 Java 中 finally 块的另一个示例
public class HelloWorld { public static void main(String []args) { try { int data = 25/5; System.out.println(data); } catch(NullPointerException e) { System.out.println(e); } finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } }
上述代码示例将产生以下结果。
5 finally block is always executed rest of the code...
java_exceptions.html