简体   繁体   English

在Main函数中,try块引发异常后,如何使其继续执行下一个try块

[英]In Main function, after a try block throws an exception how can I make it keep on execute the next try block

In Main function, after a try_block throws an exception the function is supposed to be break. 在Main函数中,try_block引发异常后,该函数应被中断。 My question is how can I make it keep on executing to the next try_block. 我的问题是如何使它继续执行到下一个try_block。 Below I'm giving an example: 下面我举一个例子:

public static void main(String [] s){
    ABC aBC = new ABC();
    try {
        aBC.execute();
    } catch (Exception e) {
        _log.error(ErrorCodeEnum.ERROR,
                "XXXXXXX!!! in " + new Date(),e);
    }
    BCD bCD = new BCD();
    try {
        bCD.execute();
    } catch (Exception e) {
        _log.error(ErrorCodeEnum.ERROR,
                "YYYYYYYYYYY!!! in " + new Date(),e);
    }
}

The code should work as it stands - ie the second block should still get executed if the first block throws and catches an Exception. 该代码应按原样运行-即,如果第一个块引发并捕获到异常,则第二个块仍应执行。

However you might want to consider catching Throwable rather than Exception if you truly want to catch everything. 但是,如果您确实想捕获所有内容,则可能要考虑捕获Throwable而不是Exception In particular, java.lang.Error is not a subclass of Exception, but is a subclass of Throwable. 特别是, java.lang.Error不是Exception的子类,而是Throwable的子类。

Just to be sure, you can wrap the statements you want executed in a finally block as follows: 可以肯定的是,可以将要执行的语句包装在finally块中,如下所示:

ABC aBC = new ABC();

try
{
    aBC.execute();
}
catch (Exception e)
{
    _log.error(ErrorCodeEnum.ERROR, "XXXXXXX!!! in " + new Date(), e);
}
finally
{
    BCD bCD = new BCD();

    try
    {
        bCD.execute();
    }
    catch (Exception e)
    {
        _log.error(ErrorCodeEnum.ERROR, "YYYYYYYYYYY!!! in " + new Date(), e);
    }
}

The statements in the finally block will get executed regardless if an exception occurs in the outer try block. 无论外部try块中是否发生异常,都将执行finally块中的语句。

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

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