java - Catching UnknownHostException which is the cause of an exception -


in program of interest, during execution of method() http related exceptions can occur. due something, method set able throw expexception. interest in specific type of exception, i.e. unknownhostexception, can accessed using

if (e.getcause().getcause().getcause() instanceof unknownhostexception) 

which hope agree nasty way. thus, 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, hoping described below. unfortunately, eclipse yells

unreachable catch block unknownhostexception. exception never thrown try statement.

is there me? don't want use getcause()^3.

an addition: big big project , i'm new newbie , rather not mess outside classes, "main".

my program like:

public class exportexception extends exception;  class sth{   method() throws expexception; }  class main{   try{     method()   } catch(unknownhostexception e){     dosth();   } catch(expexceptione){     dosthelse();   } 

unknownhostexception subtype of ioexception checked exception.

method throws checked exceptions must declare them in throws declaration.

consequently, when call method not have throws unknownhostexception in declaration, never catch exception - code unreachable , compiler correct.

here can see how nicely check if exception cause contains 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();     } } 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -