我有以下人为的代码:
class Exception
{
public static void main(String args[])
{
int x = 10;
int y = 0;
int result;
try{
result = x / y;
}
catch(ArithmeticException e){
System.out.println("Throwing the exception");
throw new ArithmeticException();
}
catch(Exception ae){
System.out.println("Caught the rethrown exception");
}
}
}
第一个catch块重新抛出捕获的异常。然而,编译器要求“不兼容类型”和“可投掷”。为什么会出现此错误?
只需从Exception to Exception1.
更改您的班级名称
它看起来像名称冲突的问题。
您的命名约定策略是反对Java标识符定义规则。
意思是,你不能给出已经由图书馆给出的名字。这里,班级名称。
你的Exception
类隐藏了java.lang.Exception
,你试图将自己的类作为异常。您应该抛出一个扩展java.lang.Exception类的对象。
只需使用java.lang.Exception更改Exception
catch(java.lang.Exception ae)
或者更改隐藏java.lang.Exception
的类的名称
试试这个
将您的类名从Exception更改为另一个用户定义名称。
它是名称冲突的问题,因为Exception是内置的
java中的类,因此您不能在源代码中使用相同的名称。
就像你不能在java中使用关键字作为标识符一样。异常不是关键字,但它已经用作类标识符。
当一个函数可以抛出异常时,你需要在函数头中声明它。
见https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html