自定义异常
模仿上题中NegativeAmountException自定义异常的写法,根据下面要求写程序。
1) 自定义异常OnlyOneException与NoOprandException,并补充各自类的构造函数,参数用于保存异常发生时候的信息;
2) 添加main方法,从命令行参数读入两个数据,计算这两个数据的和并输出。
3) 如果参数的数目只要一个,抛出OnlyOneException异常并退出程序的执行;如果没有参数 ,抛出NoOprandException异常并退出程序的执行;
class OnlyOneException extends Exception{
public OnlyOneException(String[] a){
super("参数唯一"+a); }
}
class NoOprandException extends Exception{
public NoOprandException(String[] b){
super("没有参数"+b);
}
}
public class Account{
int x,y,sum;
public void sum(String[] a)throws OnlyOneException,NoOprandException{
if(a.length==0){ throw new NoOprandException(a);
}
if(a.length==1){
throw new OnlyOneException(a);
}
x = Integer.parseInt(a[0]);
y=Integer.parseInt(a[1]);
sum=x+y;
System.out.println(sum);
}
public static void main(String[] args) throws OnlyOneException, NoOprandException {
Account p=new Account();
try{
p.sum(args);
}catch(NoOprandException e){ System.out.println(e.getMessage());
}catch(OnlyOneException e){ System.out.println(e.getMessage());
}
}
}