从被调用的方法中捕获异常

时间:2014-09-17 09:12:54

标签: java exception methods

对于程序流程来说,这一直困扰着我一段时间。

我想知道是否有可能从方法中捕获错误,以阻止它执行通常会遵循它的方法,就像我无法开始工作的示例一样。

public class MyClass {

   public static void main(String[] args) {

      // this method catches an exception and stops running
      method01();

      // this method will continue anyway which I don't want
      method02();

   };

};

我通常会有一个静态int变量,它会在程序运行时初始化为0,然后如果一个方法捕获异常,它将增加该int,并且每个方法只有在int为0时才会运行。

这有效,但我只是想知道是否可以用异常处理替换int shindig。

4 个答案:

答案 0 :(得分:1)

你可以尝试:

try {
    method01()
} catch (final Exception e) {
    // do something
    return; ///stop processing exit
}

method01将抛出异常:

private void method01() throws Exception {
// something
}

答案 1 :(得分:1)

取决于您的方法真正做什么。

如果您的程序在出现异常时也应该继续工作(例如NumberFormatException解析输入时或一般checked exception)很多人会建议您not use exception for flow control但是恕我直言,在非常明确的情况下(如NumberFormatException),流程可由try catch语句和例外控制,这完全取决于你。

这样做的方法是使用方法返回参数(同样@Nikola answer以这种方式工作,重点是使用catch的{​​{1}}部分作为流控制:

try catch

NB:您应该仅在明确定义的情况下使用此方法!如果文件在打开时可以在目录中不存在(选中FileNotFoundException),则可以使用此方法。如果文件应该在那里而不是,那么异常必须停止程序。

答案 2 :(得分:1)

如果您只想在发生异常时终止整个程序,则只需要抛出 RuntimeException 而无需进一步声明。还有用于显式异常类型的专用子类,例如 NullPointerException IllegalStateException 。请参阅"直接已知子类" JavaDoc中的部分。

public class MyClass {

    public static void main(String[] args) {
        method01();
        method02(); //method02 won't be called in case of an exception
    }

    private static void method01() {
        // ...
        if (true) // something goes wrong
            throw new RuntimeException();
        // further code won't be executed in case of an exception
    }

    private static void method02() {
        System.out.println("method02 called");
    }
}

可选择使用 try-catch-block 来处理异常:

    public static void main(String[] args) {
        try {
            method01();
            method02(); // method02 won't be called in case of an exception
        } catch (Exception e) {
            System.err.println("something went wrong");
        }
    }

    // other code keeps unchanged...

如果要强制执行异常处理,则必须抛出 Exception 的子类,该子类不是从 RuntimeException 派生的。但是必须在Signature方法中声明这些异常。

    private static void method01() throws IOException {
            throw new IOException();
    }

答案 3 :(得分:0)

您将method01method02放入同一try块:

public class MyClass {

    public static void main(String[] args) {
        try {
            // This method catches an exception and stops running.
            method01();
            // This method will not continue if method01 have exception.
            method02();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

// declare method01, method02, others...

}

注意:您在代码块(};};)

的末尾有错误