【P257】编写应用程序,从命令行输入两个小数参数,求它们的商。要求程序中捕捉NumberFormatException异常和ArithmeticException异常。
1 public class Exception{ 2 public static void main(String[] args) { 3 try{ 4 double i=Double.parseDouble(args[0]); 5 double j=Double.parseDouble(args[1]); 6 if(j==0)throw new ArithmeticException(); 7 double result=i/j; 8 System.out.println(result); 9 } 10 catch(ArithmeticException ae){ 11 System.out.println("除数不能为零!"); 12 } 13 catch(NumberFormatException nfe){ 14 System.out.println("请输入两个小数!"); 15 } 16 } 17 }
程序运行结果
【练习】
1 class Math{ 2 public double div(int i,int j) throws ArithmeticException,NumberFormatException{ 3 System.out.println("***** 计算开始 *****") ; 4 double temp = 0 ; 5 try{ 6 temp = i / j ; // 计算,但是此处有可能出现异常 7 }catch(ArithmeticException ae){ 8 throw ae ; 9 }catch(NumberFormatException be){ 10 throw be ; 11 }finally{ 12 System.out.println("***** 计算结束 *****") ; 13 } 14 return temp ; 15 } 16 } 17 public class Exception{ 18 public static void main(String args[]){ 19 Math m = new Math() ; 20 try{ 21 System.out.println("除法操作:" + m.div(10,0)) ; 22 }catch(NumberFormatException ae){ 23 System.out.println("请输入两个小数!"); 24 }catch(ArithmeticException be){ 25 System.out.println("除数不能为零!"); 26 } 27 } 28 }