sys_debug
sys_debug

Reputation: 4003

java exception arraylist iteration

I have a class that is created for the sole purpose of hadnling notifications for system x. Now when am carrying out operations in system x, n number of exceptions may be generated. I created ArrayList in my notification class to store all these exceptions. I later want to iterate over that list to check for various types of exceptions. E.g. I want to iterate and see if exception for sqlConnection occured, and then for next exception which may be SQL query, and so on.

How can this be achieved? The idea is like this:

if exception for sqlconnection was found
    exceptionMessage += "Connection Failed";
if exception for whatever was found
    exceptionMessage += "whatever exception"

etc...

Thanks,

Upvotes: 2

Views: 226

Answers (1)

Stephen C
Stephen C

Reputation: 719238

I can think of a number of ways to do this:

1) You can discriminate the different kinds of exception using instanceof; e.g.

if (e instanceof Exception) {
    if (e instanceof IOException) {
        if (e instanceof FileNotFoundException) {
            ...
        } else ...
    } else ...
} else ...

2) You can discriminate using a Map; e.g.

Map <Class, Integer> map = new HashMap<Class, Integer>();
map.put(FileNotFoundException.class, 1);
map.put(NullPointerException.class, 2);
...

Integer action = map.get(ex.getClass());
if (action != null) {
    switch(action) {
    case 1:
        ....
    case 2:
        ...
    }
}

3) In Java 7, you can discriminate by switching on the name of the exception class.

4) In Java 7 (or indeed earlier Java versions ... though the '|' is a Java 7-ism) you can throw the exception and use try {} catch to discriminate it.

Throwable ex = ...
try {
    throw ex;
} catch (IOException | InvalidArgumentException e) {
    ...
} catch (NullPointerException e) {
    ...
} catch (Throwable e) {
    // catch all
}

(The last option is arguably "using exceptions for normal control flow" ... but I believe that it should have comparable performance to the other options. The majority of the cost of using exceptions is incurred in the creation of the exception instance, and we're not doing that. We're rethrowing an exception that was created previously.)

Upvotes: 2

Related Questions