我正在使用 JDK8 在 macOS 上工作。
在 catch 中,我必须给出异常的完整名称,例如 在这种情况下 (ArithmeticException e) 而不是 (Exception e) 运行代码。
如果我使用(异常 e),它会给出一个我在 Windows 操作系统上没有遇到的错误。
这是为什么? 我应该如何解决这个问题?
该代码在使用 JDK8 的 Windows 操作系统上完美运行。 在 macOS 上,如果给出了异常的正确名称 (ArithmeticException e),则可以完美运行。
import java.util.*;
public class ExceptionDemo
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("enter first number:");
a=sc.nextInt();
System.out.println("enter second number:");
b=sc.nextInt();
try
{
c=a/b;
System.out.println("Result is:"+c);
}
catch(Exception e)
{
System.out.println("second number cannot be zero/0 "+e);
}
System.out.println("still running");
}
}
这是我收到的错误,如下所示:
incompatible types: Exception cannot be converted to Throwable catch(Exception e)
最佳答案
catch(java.lang.Exception e) {
// handle e
}
如果您不确定导入什么内容以及将在 Exception
名称下使用什么类,请使用完全限定名称。
名称Exception
对于您的应用程序来说看起来太宽泛。 [YourApplicationName]Exception
将是您的异常层次结构的一个更干净且无冲突的根(如果您想拥有一个)。
关于java - 异常无法转换为 Throwable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57623335/