Java 为什么自定义异常不';你没听清楚吗?(爪哇)
请看下面的代码行:Java 为什么自定义异常不';你没听清楚吗?(爪哇),java,exception,arithmeticexception,Java,Exception,Arithmeticexception,请看下面的代码行: public void methodBla(){ try{ system.out.println(2/0); { catch(MyArithmeticException me){ system.out.println("Error: My exception"); } catch(Exception a){ system.out.println("Error: gene
public void methodBla(){
try{
system.out.println(2/0);
{
catch(MyArithmeticException me){
system.out.println("Error: My exception");
}
catch(Exception a){
system.out.println("Error: general exception");
}
}
我不明白为什么,当我试图用自定义类捕获算术异常时:myarithmetricexception扩展了arithmetricexception
Public class MyArithmeticException extends ArithmeticException{
public MyArithmeticException(String str){
super("My Exception " + str);
}
}
MyArrithmeticException没有捕获它,它只捕获第二个“捕获”(捕获(异常a))
谢谢
Z这很简单,因为语句
2/0
不会抛出myarithmetricexception
。它抛出算术异常
,由于您没有捕获算术异常
,它被第二个捕获捕获
java语言不知道是否要从任何语言定义的异常派生自己的异常类型。因此,如果您需要抛出自己的类型,您应该捕获它并将其作为算术异常重新抛出:
public void methodBla(){
try{
try{
system.out.println(2/0);
catch(ArithmeticException e){
throw new MyArithmeticException(e);
}
}
catch(MyArithmeticException me){
system.out.println("Error: My exception");
}
catch(Exception a){
system.out.println("Error: general exception");
}
}
祝你好运。问题是会抛出一个算术异常。不是“MyAritmeticException”,所以它不能被第一个catch子句捕获,所以它会导致第二个catch子句
换句话说,2/0将抛出一个aritimeException,它是异常的超类,因此它不会触发myaritimeException捕获块,因为它是一个子类
如果您想自定义异常消息,可以在catch语句中执行,您可以通过exception#getMessage()
或exception#getLocalizedMessage()获取消息代码>(可以找到两者的区别)这是因为division的实现不知道您的自定义异常类型,因此永远不会抛出它的实例。改为捕获arithmetricexception
。因为您的异常myarithmetricexception
从未被抛出。亲爱的@AndyTurner:您指的是哪一部分?@STaefi我指的是我将Arithmatic
的所有用法都固定到了算术中,然后您将其还原。@AndyTurner:哦,我的错,我会自己更正它。谢谢你的提示。对不起。@ZivRu随时都可以!如果您需要进一步的帮助,请随时问我!