在Java编程中,如何使用finally
块来捕捉异常?
此示例显示如何使用finally
块来通过使用e.getMessage()
捕获运行时异常(Illegalargumentexception)。
package com.yiibai;
public class UseOfFinally { public static void main(String[] argv) { new UseOfFinally().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
Error: (Don't like type 1).
All done
java.lang.Object@2a139a55
示例-2
以下是java中使用finally
块捕捉异常的另一个示例:
package com.yiibai;
public class UseOfFinally2 { 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...