title: Android: How to check for a specific exception?
body: <p>How to check for a specific exception, e.g. <code>SocketException</code> with message <code>"Socket closed"</code>? We can compare strings like this:</p>
  
  <pre><code>if (exception.getMessage().equals("Socket closed"))...
  </code></pre>
  
  <p>but is there some more elegant method, like comparing error codes, or comparison with constant exception value?</p>
  
  <p>Except if <code>SocketException</code> is always <code>"Socket closed"</code>, but in docs it states that this class is a superclass for all socket exceptions, so there is more than one.</p>
  
  <p>UPDATE:
  I don't want to check for exception class. If I do, I would use specialized <code>catch</code> rather than to check tor a class explicitly:</p>
  
  <pre><code>catch (SocketException ex) { ... }
  </code></pre>
  
  <p>I want some more elegant method to distinct two exceptions which are instances of the same class, not by comparing strings like this:</p>
  
  <pre><code>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")) { ... }
  }
  </code></pre>
  
  <p>In this particular case I throw exceptions to show what is it about, but in reality it can be code not controlled by me.</p>
  
  <p>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.</p>