尝试捕获继续执行异常

Jaf*_*Ali 0 java exception-handling exception

这个问题在接受采访时被问到我.在下面的代码段中,异常发生在try块的第三行.问题是如何使第4行执行.第三行应该在catch块本身.他们给了我一个"使用投掷和投掷"的提示.

    public void testCase() throws NullPointerException{
        try{
            System.out.println("Start");
            String out = null;
            out.toString();
            System.out.println("Stop");

        }catch(NullPointerException e){
            System.out.println("Exception");
        }
    }
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙.提前致谢.

TS-*_*TS- 6

首先,异常发生在try块的第三行 - 在out.toString()第二行,而不是第二行.

我假设你想要第四行执行(即打印停止)

如果您想简单地打印Stop,有不同的方法可以执行下一行(打印停止):

 public static void testCase() throws NullPointerException{
        try{
            System.out.println("Start");
            String out = null;
            out.toString();
            System.out.println("Stop");

        }catch(NullPointerException e){
            System.out.println("Stop");
            System.out.println("Exception");
        }
    }
Run Code Online (Sandbox Code Playgroud)

或给出暗示

第三行应该在catch块本身

 public static void testCase() throws NullPointerException{
        try{
            System.out.println("Start");
            String out = null;
            Exception e = null;

            try
            {
                out.toString();
            }
            catch(Exception ex)
            {
                e = ex;
            }
            System.out.println("Stop");

            if(e != null)
                throw e;

        }catch(Exception e){
            System.out.println("Exception");
        }
    }
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以做到这一点,例如.最后阻止等等.但由于给出了有限的信息量并且目标是使其工作 - 上述内容应该足够了.