刚刚看过你那个问题,其实你的程序如果不想做异常处理,直接写成这样就可以了 class Excep { public int abc(int a, int b) { return a / b; } } class Test { public static void main(String[] args) { Excep excep = new Excep(); excep.abc(5, 0); } }
最后一个问题: public int abc(int a,int b) throws ArithmeticException { return a/b; } 我在这个方法里面也不进行处理,那它要上传给它的调用者进行处理,那和在这个方法里用try,catch,并在catch里throw有什么区别啊 public int abc(int a,int b) throws ArithmeticException { try{ return a/b; } catch(ArithmeticException{ throw e; } }
class Excep {
public int abc(int a, int b) {
return a / b;
}
}
class Test {
public static void main(String[] args) {
Excep excep = new Excep();
excep.abc(5, 0);
}
}
那么,这里有2个方法,abc和main,你要在哪个类里面处理呢?
public int abc(int a, int b) throws Exception {
try {
return a / b;
} catch (Exception e) {
// 假设你要在这里做异常处理,就在这里写代码
// 不处理,就要把异常抛出去
// 我这里做抛出
throw e;
}
}
}class Test {
public static void main(String[] args) {
Excep excep = new Excep();
try {
excep.abc(5, 0);
} catch (Exception e) {
// 假设你要在这里做异常处理,就在这里写代码
// 我在这里做处理,只友好的提醒用户,不让用户看到一大片红字
System.out.println("亲爱的feiyuxianwan(绯雨闲丸),你的程序出了一点小错,你需要联系管理员处理");
}
}
}
假设一个方法内部有throw,并且没有处理,那么方法一定要指明throws。
须知,是当你abc方法catch了某种Exception并且不想在abc方法内解决它的时候,才需要throw它出来,而throw它的直接结果就是必须要将abc方法声明成throws 某种Exception。一个方法,先有throw(并且没有被解决),才必须有throws!你为何非要先把方法定义成throws,然后拼命的思考要不要在方法内throw呢?假设abc中一个非运行时异常,既然是非运行时的,那么你肯定在代码的时候就知道可能要出这个异常,那么在abc的代码中一定会写try和catch。既然你catch了某个非运行时异常,如同我上面所问,你到底要在哪里处理?如果你要在catch中处理掉,就不用throw;如果你不想处理,那就在catch里面写throw。
public int abc(int a,int b) throws ArithmeticException
{
return a/b;
}
我在这个方法里面也不进行处理,那它要上传给它的调用者进行处理,那和在这个方法里用try,catch,并在catch里throw有什么区别啊
public int abc(int a,int b) throws ArithmeticException
{
try{
return a/b;
}
catch(ArithmeticException{
throw e;
}
}
加throws的结果,其实就是明确要求调用者:“你在调用我的时候,很可能会有异常,所以我要求你在调用的时候try并catch”。对于你上面这个小方法abc,只是rutern a/b,当然体现不出来加throw的意义。
菜鸟意见。不要笑偶,偶也是刚刚工作没多久~!!