第8次Java作业+LSYang

【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 }

 

转载于:https://www.cnblogs.com/liusiyang1126/p/5444795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值