繁体   English   中英

尝试捕获块给出编译错误

[英]try-catch block giving compilation error

我试图在try-catch块中添加一些代码,但是在编译时失败,并且我没有弄错。

try 
{ 
    int x = 0; 
    int y = 5 / x; 
} 
catch (Exception e) 
{
    System.out.println("Exception"); 
} 
catch (ArithmeticException ae) 
{
    System.out.println(" Arithmetic Exception"); 
} 
System.out.println("finished");

有人可以帮忙吗?

采用 :

try 
{ 
    int x = 0; 
    int y = 5 / x; 
} 
catch (ArithmeticException ae) 
{
    System.out.println(" Arithmetic Exception"); 
} 
catch (Exception e) 
{
    System.out.println("Exception"); 
} 

System.out.println("finished");

在处理异常时,必须在捕获子类异常之后捕获更广泛的异常(超类异常,在您的情况下,Exception是ArthmeticException的超类)。 否则,异常将被较宽/父异常捕获块捕获,并且后面的代码将不可访问。 因此它将无法编译。

异常hierearchy说

ONCE YOU HAVE CAUGHT AN EXCEPTION IT NEEDS NOT TO BE CAUGHT AGAIN

因为您已经在第一个catch块中捕获了Exception

因此,您的下一个捕获块是没有用的

您应该首先捕获子类,然后为其余可能的其他异常捕获父类Exception

尝试这个

try 
{ 
    // your code throwing exception
} 
catch (ArithmeticException ae) 
{
    // do something
} 
catch (Exception e) 
{
    // do something
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM