1

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.

This works but I was just wondering if I could replace the int shindig with exception handling.

TheLovelySausage
  • 3,017
  • 5
  • 45
  • 80

4 Answers4

1

Can you try:

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

the method01 will throw Exception:

private void method01() throws Exception {
// something
}
Nikola Dimitrovski
  • 690
  • 1
  • 8
  • 20
  • Might I suggest a custom unchecked exception, so that there is no requirement to wrap all instances of method01 in cases where this is required to propogate up. and also can be more descriptive about the actual problem. :) – Guy Flavell Sep 17 '14 at 09:18
  • sure regarding to the implementation he can change the Exception – Nikola Dimitrovski Sep 17 '14 at 09:21
  • This style worked really well, I didn't realize that when a Method is given "throws Exception" that it would throw the exception found inside the method to the try statement it is executed inside. – TheLovelySausage Sep 17 '14 at 11:38
1

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.

Community
  • 1
  • 1
Narmer
  • 1,386
  • 6
  • 16
  • The solution you've provided above looks sort of, kinda, in a way, not really, almost a combination of using variables alongside an exception for flow control which is great although a little bit overkill for my needs. This would be a perfect way to execute a Method that depends on a different Method being successful and I can definitely use this. – TheLovelySausage Sep 17 '14 at 11:51
1

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. There are also specialized sub classes for explicit types of exceptions, like NullPointerException or IllegalStateException. See the "Direct Known Subclasses" section in the 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:

    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. But those exceptions have to be declared within the method Signature.

    private static void method01() throws IOException {
            throw new IOException();
    }
Adam Taras
  • 1,115
  • 1
  • 11
  • 15
  • I try to stay away from RuntimeExceptions just for personal preference. The try-catch-block however is exactly what I'm looking for, similar to Nikola's answer. Awesome – TheLovelySausage Sep 17 '14 at 11:55
0

You put method01 and method02 in to same try block:

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

Do Nhu Vy
  • 33,131
  • 37
  • 143
  • 202
  • Although ending classes with a semi-colon is not necessary it is not a mistake. I use them intentionally just to make the end of classes more clear. This was the format I first tried but I see that the try statement will only catch the exception that the method throws if the method is specified an exception to throw in the methods parameters so this is technically correct – TheLovelySausage Sep 17 '14 at 11:45