Catching an Exception from a called Method

前端 未结 4 682
情歌与酒
情歌与酒 2021-01-24 06:30

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 i

4条回答
  •  囚心锁ツ
    2021-01-24 07:05

    Depends on what your method really does.

    If your program should continue working also when an exception arise (e.g. 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.

    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):

    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. If the file SHOULD be there and its not, the exception MUST stop the program.

提交回复
热议问题