简体   繁体   English

尝试捕获块给出编译错误

[英]try-catch block giving compilation error

I am trying to add some of my code in try-catch block, but it fails at compilation and I am not getting what is wrong. 我试图在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");

Can anybody help please. 有人可以帮忙吗?

Use : 采用 :

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");

While handling exceptions, wider exceptions(super class exception, in your case Exception is super class of ArthmeticException) must be catch after catching sub-class exceptions. 在处理异常时,必须在捕获子类异常之后捕获更广泛的异常(超类异常,在您的情况下,Exception是ArthmeticException的超类)。 Otherwise, exception will be caught by wider/parent exception catch block and latter code will be unreachable. 否则,异常将被较宽/父异常捕获块捕获,并且后面的代码将不可访问。 So it will not compile. 因此它将无法编译。

exception hierearchy says 异常hierearchy说

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

since you already are catching Exception in your first catch block 因为您已经在第一个catch块中捕获了Exception

thus your next catch block is useless 因此,您的下一个捕获块是没有用的

you should catch child classes first , then for the remaining possible other exception should catch parent Exception class 您应该首先捕获子类,然后为其余可能的其他异常捕获父类Exception

try this 尝试这个

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