1

I hava a program that works and catches the error, however I am looking to make it finish the loop and not stop when the error is caught.

public class myClass {
    int[] table;
    int size;

    public myClass(int size) {
        this.size = size;
        table = new int[size];
    }

    public static void main(String[] args) {
        int[] sizes = {5, 3, -2, 2, 6, -4};
        myClass testInst;
        try {
            for (int i = 0; i < 6; i++) {
                testInst = new myClass(sizes[i]);
                System.out.println("New example size " + testInst.size);
            }
        }catch (NegativeArraySizeException e) {
            System.out.println("Must not be a negative.");
        }
    }
}

The error happens as the array size is negative, but how do I then continue to finish the loop?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

3 Answers3

4

however I am looking to make it finish the loop and not stop when the error is caught.

Okay. Move the try and catch into the loop then.

for (int i = 0; i < 6; i++) {
    try {
        testInst = new myClass(sizes[i]);
        System.out.println("New example size " + testInst.size);
    } catch (NegativeArraySizeException e) {
        System.out.println("Must not be a negative.");
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

First you specify where location in your program can throw an exception. Second specify how to handle the exception, for example specify that you want to throw that exception or just write a log and execution continue. Third, you specify when that the exception will be handle. At your code try-catch can be in constructor, or can be in loop and around of below code, to reach to your goal. testInst = new myClass(sizes[i]);

0

Just put the try-catch block inside the loop. This way if an error is thrown, you can handle it and just continue the loop. Here's the code:

    public class myClass {
    int[] table;
    int size;

    public myClass(int size) {
        this.size = size;
        table = new int[size];
    }

    public static void main(String[] args) {
        int[] sizes = {5, 3, -2, 2, 6, -4};
        myClass testInst;
            for (int i = 0; i < 6; i++) {
                try {
                    testInst = new myClass(sizes[i]);
                    System.out.println("New example size " + testInst.size);
                } catch(NegativeArraySizeException e) {
                    System.out.println("Must not be a negative.");
                    continue;
                }
        }
    }
}
Prashant Pandey
  • 4,332
  • 3
  • 26
  • 44