如何捕获在 catch 子句中抛出的异常?

How to catch an exception that was thrown inside a catch clause?

try {

        throw new SomeException();

    }

    catch (SomeException e) {

        System.out.println("reached once");
        throw e;
    }

    catch (Exception e) {
        System.out.println("reached twice");
    }

此代码仅显示 "reached once",即使在第一个 catch 子句中再次抛出异常。如何解决这个问题以便执行两个 catch 子句?

PS:上面的代码是我遇到的一个普遍问题,我不得不将它应用到更大的代码中,其中包含大约 5 或 6 个捕获不同异常的 catch 子句,但最后,在循环中的某个点我需要再次抛出异常。

只需在catch中再添加一个try catch即可。

try {
    try {

        throw new NullPointerException();

    } catch (NullPointerException e) {
        System.out.println("reached once");

        throw e;
    }
} catch (SomeOtherException ex) {}

您必须用 try/catch 块

包围所有可能抛出 Exception 的代码
    try {

            throw new NullPointerException();
        }
        catch (NullPointerException e) {
            System.out.println("reached once");
            try{
                throw e;
            }
            catch (Exception ex) {
                System.out.println("reached twice");
            }
        }