2

In program of interest, during execution of a method() some HTTP related exceptions can occur. Due to something, that method was set to be able to throw ExpException. My interest is only in specific type of exception, i.e. UnknownHostException, which can be accessed by using

if (e.getCause().getCause().getCause() instanceof UnknownHostException)

which I hope you agree is very nasty way. Thus, this works fine:

public class ExportException extends Exception;

class sth{
  method() throws ExpException;
}

class main{
  try{
    method()
  } catch(ExpExceptione e){
    if (e.getCause().getCause().getCause() instanceof UnknownHostException){
        doSthElse();
    }
  }

However, I was hoping to do as described below. Unfortunately, Eclipse yells

Unreachable catch block for UnknownHostException. This exception is never thrown from the try statement.

Is there any help for me? I don't want to use getCause()^3.

An addition: this is a big big project and I'm the new newbie and would rather not mess with outside classes, but just the "main".

My program is something like:

public class ExportException extends Exception;

class sth{
  method() throws ExpException;
}

class main{
  try{
    method()
  } catch(UnknownHostException e){
    doSth();
  } catch(ExpExceptione){
    doSthElse();
  }
Dawid Laszuk
  • 1,773
  • 21
  • 39
  • This exception is not being thrown. This seems obvious from the error message. – Tim Biegeleisen Jan 28 '16 at 13:10
  • Well, if the exception is the *cause* of the exception you catch, then it is not thrown where you are trying to catch it. Either you change the part of the code that catches it and makes it the cause of another exception, or you'll need to get the cause as you have been doing. – RealSkeptic Jan 28 '16 at 13:13

1 Answers1

2

UnknownHostException is a subtype of IOException which is checked exception.

Method that throws checked exceptions must declare them in throws declaration.

Consequently, when you call a method that does not have throws UnknownHostException in declaration, you will never catch this exception - code is unreachable and compiler is correct.

Here you can see how to nicely check if exception cause contains any specific exception.

static boolean hasCause(Throwable e, Class<? extends Throwable> cl) {
    return cl.isInstance(e) || e.getCause() != null && hasCause(e.getCause(), cl);
}

catch(ExpException e) {
    if (hasCause(e, UnknownHostException.class)) {
       doSmth();
    } else {
       doSmthElse();
    }
}
Community
  • 1
  • 1
AdamSkywalker
  • 11,408
  • 3
  • 38
  • 76