public static void show() throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("请输入被除数:");
int num = input.nextInt();
System.out.println("请输入除数");
int num1 = input.nextInt();
System.out.println(String.format("%d / %d = %d",num,num1,num/num1) );
}
public static void main(String[] args) {
try{
show();
}catch(Exception e){
System.out.println("输入错误,除数和被除数必须是整数");
System.out.println("未知异常");
e.printStackTrace();
}finally{
System.out.println("谢谢使用本程序");
}
}
方法后面没加throws Exception ,main里面也捕捉到异常了,怎么回事?
追答默认为把exception往上一级抛。所以throw exception。但如果你没加这一句。main方法里,可以不用try catch。如果加了。main方法必须try catch。或者再在后面throw exception。
这个要看经验。。。你现在很难理解。
我觉得应该是这样。
如果你的方法是别人要调用的,你又明知道可能会出错异常的代码。比如算数。输入输出流。当然,你要是简单到可以肯定不会出异常,就可以不做处理。你就应该把代码内部先try catch。然后再throw 一个自定义异常。这样别人就知道出在哪里。
ublic static void show() throws BusinessException{
try{
Scanner input = new Scanner(System.in);
System.out.println("请输入被除数:");
int num = input.nextInt();
System.out.println("请输入除数");
int num1 = input.nextInt();
System.out.println(String.format("%d / %d = %d",num,num1,num/num1) );
}catch(Exception e){
throw new BusinessException("显示异常",e);
}
}
BusinessException是自定义异常类。
有点明白,又不太明白,你说的跟编程思想上的一样难懂!
追答不用纠结。代码写多了,就会懂得。。
我的方法是类方法,不加也可以运行
追答比如类名为A 这样A.show()