异常处理:
java中通过try····catch语句来实现抛出捕捉异常来实现程序的正常运行,异常包括error和exception异常错误。可以通过自定义异常类,自定义异常类继承exception类,来实现异常处理的操作。
实例代码:
import javax.swing.*; class AboutException { public static void main(String[] a) { int i=1, j=0, k; k=i/j; try { k = i/j; } 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"); } } }
多层异常捕获:
对于多层异常捕获,是寻找跑出的异常如果外层没有,继续跳出,知道找到抛出的错误。如果找到了,则继续进行以下的代码。
源代码:
package lianxi; public class APP{ public static void main(String[] args) { try { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArithmeticException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch"); } throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("发生ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch"); } } } 结果: ArrayIndexOutOfBoundsException/外层try-catch
public class APP{ public static void main(String[] args) { try { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch"); } throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("发生ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch"); } } }
结果:
ArrayIndexOutOfBoundsException/内层try-catch 发生ArithmeticException
当多个finally嵌套时,抛出一条异常,系统会实现捕捉该条异常,之后会依次执行finally中的语句。
源代码:
public class Jiecheng { public static void main(String[] args) { int result; try { System.out.println("in Level 1"); try { System.out.println("in 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"); } } catch (Exception e) { System.out.println("Level 2:" + e.getClass().toString()); } finally { System.out.println("In Level 2 finally"); } } catch (Exception e) { System.out.println("Level 1:" + e.getClass().toString()); } finally { System.out.println("In Level 1 finally"); } } } 运行结果: in Level 1 in Level 2 in Level 3 Level 3:class java.lang.ArithmeticException In Level 3 finally In Level 2 finally In Level 1 finally
finally语句不一定会执行,可以在之前实行终止程序的语句System.exit(0);
public class Jiecheng { public static void main(String[] args) { try{ System.out.println("in main"); throw new Exception("Exception is thrown in main"); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(0); } finally { System.out.println("in finally"); } } } 运行结果: in main Exception is thrown in main