简体   繁体   English

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

[英]Catching an Exception from a called Method

This is something that's been bugging me for a while with regards to Program Flow. 对于程序流程来说,这一直困扰着我一段时间。

I wanted to know if it's possible to catch an error from a Method in order to stop it from executing the Method that would normally follow it like the example bellow that I can't get to work. 我想知道是否有可能从方法中捕获错误,以阻止它执行通常会跟随它的方法,就像我无法工作的示例。

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

   };

};

I would normally have a static int variable that will initialize as 0 when the program is run and then if a method ever catches an exception it will increment that int and each method will only run if the int is 0. 我通常会有一个静态int变量,它会在程序运行时初始化为0,然后如果一个方法捕获异常,它将增加该int,并且每个方法只有在int为0时才会运行。

This works but I was just wondering if I could replace the int shindig with exception handling. 这有效,但我只是想知道我是否可以用异常处理替换int shindig。

Can you try: 你能试一下吗:

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

the method01 will throw Exception: method01将抛出异常:

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

Depends on what your method really does. 取决于你的方法真正做什么。

If your program should continue working also when an exception arise (eg NumberFormatException when parsing an input or in general a checked exception ) a lot of people will suggest you to not use exception for flow control , but IMHO in very well defined cases (like NumberFormatException ) the flow CAN be controlled by try catch statements and exceptions, it's really up to you. 如果你的程序在出现异常时也应该继续工作(例如解析输入时的NumberFormatException或者通常是一个已检查的异常 )很多人会建议你不要使用异常进行流量控制 ,而是在很好定义的情况下使用 IMHO(比如NumberFormatException )流程可以通过try catch语句和异常来控制,这完全取决于你。

A way to do so is to use the method returned parameter (also @Nikola answer works in this way, the point is to use the catch part of a try catch as flow control): 一种方法是使用方法返回参数(也是@Nikola答案以这种方式工作,重点是使用try catchcatch部分作为流控件):

public class MyClass {

   public static void main(String[] args) {

      if(method01()) method02();

   };
};

public boolean method01(){
    try{
        //some business
    }catch(MyCheckedException e){
        e.printStackTrace();
        return false;
    }
    return true;
}

NB: You should use this approach only in well defined situations! 注意:你应该只在明确定义的情况下使用这种方法! If a file CAN be absent in a directory while opening it (checked FileNotFoundException ), you COULD use this approach. 如果打开文件时目录中可能没有文件(选中FileNotFoundException ),则可以使用此方法。 If the file SHOULD be there and its not, the exception MUST stop the program. 如果文件应该在那里而不是,那么异常必须停止程序。

If you only want to terminate the whole program in case of an exception you just need to throw a RuntimeException without any further declaration. 如果您只想在异常的情况下终止整个程序,您只需要抛出RuntimeException而不需要进一步声明。 There are also specialized sub classes for explicit types of exceptions, like NullPointerException or IllegalStateException . 还有用于显式异常类型的专用子类,如NullPointerExceptionIllegalStateException See the "Direct Known Subclasses" section in the JavaDoc . 请参阅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");
    }
}

Optionally it is possible to handle the exception with a try-catch-block : 可选地,可以使用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...

If you want to enforce exception handling, you have to throw a subclass of Exception that is not derived from RuntimeException . 如果要强制执行异常处理,则必须抛出不是从RuntimeException派生的Exception子类。 But those exceptions have to be declared within the method Signature. 但是必须在Signature方法中声明这些异常。

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

You put method01 and method02 in to same try block: 您将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...

}

Notice: You have mistakes at the end of code block ( }; }; ) 注意:你在代码块(};};)的末尾有错误

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

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