2

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,

1
  • 1
    so you want to check something like if (exception instanceof SQLException) handleSQLException(); if (exception instanceof IOException) handleIOException(); and on but in a nice and clean way Commented Apr 28, 2012 at 5:45

1 Answer 1

2

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

I already used the first approach and it worked. When the first reply came to use instanceof I did just so. and then you reply confirmed that my idea is valid. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.