'throwing exception in catch and causing a halt in flow

I have a code and my objective is this:

public class Stream {
    public static void main(String args[]) throws ArithmeticException {

        test2();
        test3();
    }

    public static void test() {
        try {
            int[] myNumbers = {1, 2, 3};
            System.out.println(myNumbers[10]);
        } catch (Exception e) {
            System.out.println("Something went wrong.");
        }
    }

    public static void test2() {
        try {
            test(); //may throw exception
        }
        //handling the exception
        catch (Exception e) {
            //System.out.println(e);
            throw new ArithmeticException("Person is not eligible to vote");
        }
    }

    public static void test3() {
        System.out.println("test3");

    }
}

Now, I actually, don't want test3() to be invoked in case test2() fails and it should throw the error. As seen, Im invoking test2(), which is calling test() in try block and since test() is catching an exception, I want the entire execution to come to halt and test3() should not be allowed to proceed with. Is there a way I can achieve? I am very new to programming and some help will be very appreciated.



Solution 1:[1]

The problem is that test() as you have written it DOES NOT allow an exception to propagate. It catches all exceptions and just prints "something went wrong".

If you want the exception to propagate, you need to change the test method to rethrow the exception, or wrap and throw it, or not catch it in the first place; i.e.

public static void test() {
    try {
        int[] myNumbers = {1, 2, 3};
        System.out.println(myNumbers[10]);
    } catch (Exception e) {
        System.out.println("Something went wrong.");
        throw e;   // rethrow
    }
}

or

public static void test() {
    try {
        int[] myNumbers = {1, 2, 3};
        System.out.println(myNumbers[10]);
    } catch (Exception e) {
        System.out.println("Something went wrong.");
        throw new SomeOtherException(e);  //wrap and throw
    }
}

or

public static void test() {
    int[] myNumbers = {1, 2, 3};
    System.out.println(myNumbers[10]);
}

Notes:

  • Printing messages to standard output in exception handlers is not something that you should in production programs.
  • You should not throw ArithmeticException for some condition that is not a genuine arithmetic exception.
  • Declaring main to throw an exception is not something that you should in production programs.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1