m.cekiera
m.cekiera

Reputation: 5395

Throwing exceptions without interrupting execution of method

I know and recognize (or I think so) the difference beetwen exception hendling by try{}catch block and throwing exceptions by classes or methods, but I wonder, if there is a way, to use throws kayword by method, and mentain the execution of this code/method after throwing exception?

I mean, like in example below:

public class Main {
    int[] array = {0,1,2};

    public static void main(String[] args){
        Main object = new Main();
        System.out.println("Dealing inside try{}catch block");
        object.dealInside();
        System.out.println("Dealing by throws keyword");
        try{
            object.throwOutside();
        }catch (ArrayIndexOutOfBoundsException ex){
        }
    }

    public void dealInside(){
         for(int i = 0; i < 6; i++){
             try{
                 System.out.println(i);
                 int r = array[i];
             }catch (ArrayIndexOutOfBoundsException ex){
             }
         }
    }

    public void throwOutside() throws ArrayIndexOutOfBoundsException{
        for(int i = 0; i < 6; i++){
            System.out.println(i);
            int r = array[i];
        }
    }
}

If there is try{}catch block inside the loop, method can proceed even if exception occur, and it print int up to 6, even if the length of array is 3. But in case of method which throws exception, once interrupted method stops.

  1. Is there a way to continue working of method, which throws exception?
  2. Is it possible, to deal at the same time, with multiple methods which throws similar/same exception, without interruption of their execution?

Upvotes: 1

Views: 2545

Answers (1)

Samrat Dutta
Samrat Dutta

Reputation: 1737

finally

This is the exact purpose of the finally block. To execute the code inside it no matter if an exception was caught before it or not. It will always execute. Write some logic to achieve what you actually want by altering the value of i perhaps inside the finally block.

try {
    //risky code
} catch(Exception ex) {
    //handle caught exception
} finally {
    //this part always executes
}

Now, the tricky bit. if you really want the for loop to keep going, even if the exception is caught in a subsequent statement, here is what you do.

for(int i = 0; i < 6; i++) {

    Thread t = new Thread(new Runnable() {
        void run() {
            try{
                 System.out.println(i);
                 int r = array[i];
             }catch (ArrayIndexOutOfBoundsException ex){
             }
        });
    t.start();
}

The for loop is running on the main thread while the risky code is in a separate thread. So, even if it encounters an exception, the main thread keeps on running as it has no idea about the exception thrown. This is a neat trick. But I don't know if it is a good idea to use it in practice though.

Upvotes: 2

Related Questions