异常处理的5个关键字:try,catch,finally,throw和throws
♦try:把要监控异常的代码放在try块里
♦catch:用来捕获异常并处理异常
1 /*file:ExceptionDemo.java;除数为零的异常处理*/ 2 public class ExceptionDemo 3 { 4 public static void main(String[] args) 5 { 6 int n1=10; 7 int n2=0; 8 try 9 {10 int result=n1/n2;11 System.out.println("两数相除的结果是:"+result);12 }13 catch(ArithmeticException ex)14 {15 System.out.println("出现除数为零的异常");16 }17 }18 }
ArithmeticException:算术异常(算术错误情形,如以上例子,以零做除数)
catch块必须和try块一起使用,catch块不能单独使用
♦多重catch块
1 /*file:ExceptionDemo2.java;多重catch块*/ 2 pubic class ExceptionDemo2 3 { 4 public static void main(String[] args) 5 { 6 try 7 { 8 int n1=Integer.parseInt(args[0]); 9 int n2=Integer.parseInt(args[1]);10 int result=n1/n2;11 System.out.println("两数相除的结果是:"+result);12 }13 catch(ArrayIndexOutOfBoundsException ex)14 {15 System.out.println("数组下标越界异常:请输入两个数");16 }17 catch(NumberFormatException ex)18 {19 System.out.println("数字格式异常:请输入两个整数");20 }21 catch(ArithmeticException ex)22 {23 System.out.println("算术异常:除数不能为零");24 }25 }26 }
ArrayIndexOutOfBoundsException:数组下标越界异常
NumberFormatException:数字格式异常
♦finally块:无论是否发生异常都必须执行
/*file:ExceptionDemo3;finally块的使用*/public calss ExceptionDemo3{ public static void main(String[] args) { int n1=10; int n2=0; try { int result=n1/n2; System.out.println("两数相除的结果是:"+result); } catch(ArithmeticException ex) { System.out.println("除数不能为零"); } finally { System.out.println("这是finally块中的代码,无论是否发生异常,必定执行"); } }}
finally不能单独使用,必须和try块一起使用。finally块包含将资源返回给系统的语句或输出消息的语句,如果引发异常,即使没有catch块与引发的异常匹配,finally块也将执行。finally块是可选的,但每个try块应该至少有一个catch块或finally块。
♦嵌套try-catch块
/*file:ExceptionDemo4;嵌套try-catch块*/public class ExceptionDemo4{ public static void main(String[] args) { try { try { int n=Integer.parseInt(args[0]); int square=n*n; System.out.println(n+"的平方是:"+aquare); } catch(ArrrayIndexOutOfBoundsException ex) { System.out.println("数组下标越界异常:请输入一个数字"); } } catch(NumberFormatException ex) { System.out.println("数字格式异常:请输入一个整数"); } }}
♦throw:throw关键字用于人为显式地抛出异常
/*file:ExceptionDemo5.java;*/public class ExceptionDemo5{ static void throwException(int n1,int n2) { try { if(n2==0) { throw new ArithmeticException("除数为零"); } System.out.println("两数相除的结果是:"+n1/n2); } catch(ArithmeticException ex) { System.out.println(ex.getMessage()); } } public static void main(String[] args) { throwException(10,0); }}
♦throw:用于在方法声明中回避该方法中不处理的异常
/*file:ExceptionDemo6.java;*/class ThrowsDemo{ public void throwsMethod(int n1,int n2) throw ArithmeticException { int result=n1/n2; }}public class ExceptionDemo6{ public static void main(String[] args) { ThrowsDemo td=new ThrowsDemo(); try { td.throwsMethod(10,0); } catch(ArithmeticException ex) { System.out.println("算术异常:除数为零"); } }}