代码如下:
import javax.swing.*; class AboutException { public static void main(String[] a) { int i=1, j=0, k; k=i/j; try { k = i/j; // Causes division-by-zero exception //throw new Exception("Hello.Exception!"); } catch ( ArithmeticException e) { System.out.println("被0除. "+ e.getMessage()); } catch (Exception e) { if (e instanceof ArithmeticException) System.out.println("被0除"); else { System.out.println(e.getMessage()); } } finally { JOptionPane.showConfirmDialog(null,"OK"); } } }
catch语句用于处理try语句中可能会发生错误的代码所发生的异常。不管是否有异常发生,finally语句都会被执行。如果没有提供合适的异常处理代码,JVM将会结束掉整个应用程序。
运行结果:
代码如下:
运行结果:
代码如下:
public class EmbededFinally { public static void main(String args[]) { int result; try { System.out.println("in Level 1"); try { System.out.println("in Level 2"); result=100/0; //Level 2 try { System.out.println("in Level 3"); result=100/0; //Level 3 } catch (Exception e) { System.out.println("Level 3:" + e.getClass().toString()); } finally { System.out.println("In Level 3 finally"); } // result=100/0; //Level 2 } catch (Exception e) { System.out.println("Level 2:" + e.getClass().toString()); } finally { System.out.println("In Level 2 finally"); } // result = 100 / 0; //level 1 } catch (Exception e) { System.out.println("Level 1:" + e.getClass().toString()); } finally { . System.out.println("In Level 1 finally"); } } }
catch语句只接受相邻的try语句抛出的错误。无论有无异常finally语句都会执行。
代码如下:
public class SystemExitAndFinally { public static void main(String[] args) { try { System.out.println("in main"); throw new Exception("Exception is thrown in main"); //System.exit(0); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(0); } finally { System.out.println("in finally"); } } }
System.exit(0)是强制退出程序,System.exit(1)是异常终止。一般情况下,无论有无异常finally语句都会执行,但此代码catch语句中有System.exit(0)强制退出程序,故不会执行finally语句。