Java中自定义抛异常的问题,求大神指点

1:Exception 异常 放在自定义的异常前面 就报错,为啥? 2:为什么传入的参数为(3 ,'a'),没有报错,结果为0,为啥? class throw_exp extends Exception{ int dev; public throw_exp(String msg, int dev){ super(msg); this.dev = dev; } public int GetDev(){ return dev; } } public class Test_throw { public static void main(String[] args) { try { int result = new Test_throw().devide(3,'b'); //int result = new Test_throw().devide(3, 0); //int result = new Test_throw().devide(3, -1); System.out.println("结果为:"+ result); } catch(throw_exp e){ System.out.println("throw_exp" + e.getMessage() + e.GetDev()); }//自定义异常 catch(ArithmeticException e){ System.out.println("ArithmeticException" + e.getMessage()); }//在算术运算中发生的异常,如除以0 catch(Exception e){ System.out.println("Exception" + e.getMessage()); } } public int devide(int x,int y) throws ArithmeticException, throw_exp{ if(y < 0) throw new throw_exp("被除数为负数",y); int result = x/y; return result; } }

第1个回答  2020-07-31
1
Exception
是所有异常的顶级父类,只要出错就属于Exception,你放在自定义异常前面,不管出什么错,肯定会先catch到Exception,后面不管catch什么错误都永远不会执行到,所以编译直接不通过
2
当你传入一个字符的时候,而定义的是int类型,那该字符会直接转换为Unicode编码,a的
字符编码
是97,b是98,3/98,结果当然是0
第2个回答  2020-01-15
你好!
1.
记住一点:子类异常必须在父类之前;
2.
你把小写字母a传进去了,系统自动转换成了int类型97,然后0除以97得多少?不用我说了吧
至于为什么a变成97,你百度一下ASCII,基础的东西
如有疑问,请追问。
相似回答