Elvedin Hamzagic
Elvedin Hamzagic

Reputation: 855

Android: How to check for a specific exception?

How to check for a specific exception, e.g. SocketException with message "Socket closed"? We can compare strings like this:

if (exception.getMessage().equals("Socket closed"))...

but is there some more elegant method, like comparing error codes, or comparison with constant exception value?

Except if SocketException is always "Socket closed", but in docs it states that this class is a superclass for all socket exceptions, so there is more than one.

UPDATE: I don't want to check for exception class. If I do, I would use specialized catch rather than to check tor a class explicitly:

catch (SocketException ex) { ... }

I want some more elegant method to distinct two exceptions which are instances of the same class, not by comparing strings like this:

try {
    int i = 2;
    if (i == 1) throw new SocketException("one");
    else if (i == 2) throw new SocketException("two");
}
catch (SocketException ex) {
    if (ex.getMessage().equals("one")) { ... }
}

In this particular case I throw exceptions to show what is it about, but in reality it can be code not controlled by me.

Also I noticed that exception message in one particular case method threw "Socket closed", in another different method threw "Socket is closed". So it's not so reliable to stick to the message either.

Upvotes: 2

Views: 2388

Answers (2)

Jim
Jim

Reputation: 10278

Your question has different approaches, depending on what you are trying to achieve. The simplest method for determining if you have the exception you want is to use instanceof since an Exception is a class as well, i.e.:

if (myException instanceof SocketException) {
    ...
}

However, you then add the requirement of the contents of the message or the possibility that the Exception thrown is actually a subclass of the Exception of interest to you. In the case of a "subclass" you can check if it is a subclass with:

if (myException instanceof SocketException && 
    myException.getClass() != SocketException.class) {
    // then I'm an instance of a subclass of SocketException, but not SocketExcpetion itself
}

Or conversely, only evaluate for the parent class:

if (myException instanceof SocketException && 
    myException.getClass() == SocketException.class) {
    // then I'm an instance of the class SocketException, and not a cubclass of SocketExcpetion!!
}

These serve as the "error codes" you seem to be looking for - the identification of the class, with certainty.

However, if you really are interested in the human-readable error contents, then the solution you have should be your implementation. That seems unlikely, but sometimes that is what is required.

Upvotes: 3

Actiwitty
Actiwitty

Reputation: 1242

You can use:

exception.getClass().getSimpleName() and compare it to SocketException

Hope this helps.

Upvotes: 0

Related Questions