java - How do I use Throwables.propagateIfInstanceOf() from Google Guava? -


the javadoc example

  try {     somemethodthatcouldthrowanything();   } catch (iknowwhattodowiththisexception e) {     handle(e);   } catch (throwable t) {     throwables.propagateifinstanceof(t, ioexception.class);     throwables.propagateifinstanceof(t, sqlexception.class);     throw throwables.propagate(t);   } 

is not concrete. how real program like? don't understand purpose of methods throwables.propagateifinstanceof(throwable, class), propagate(), propagateifpossible(). when use them?

the purpose of these methods provide convenient way deal checked exceptions.

throwables.propagate() shorthand common idiom of retrowing checked exception wrapped unchecked 1 (to avoid declaring in method's throws clause).

throwables.propagateifinstanceof() used retrow checked exceptions if types declared in throws clause of method.

in other words, code in question

public void dosomething()      throws ioexception, sqlexception {      try {         somemethodthatcouldthrowanything();     } catch (iknowwhattodowiththisexception e) {         handle(e);     } catch (throwable t) {         throwables.propagateifinstanceof(t, ioexception.class);         throwables.propagateifinstanceof(t, sqlexception.class);         throw throwables.propagate(t);     }   } 

is shorthand following code:

public void dosomething()      throws ioexception, sqlexception {      try {         somemethodthatcouldthrowanything();     } catch (iknowwhattodowiththisexception e) {         handle(e);     } catch (sqlexception ex) {         throw ex;     } catch (ioexception ex) {         throw ex;     } catch (throwable t) {         throw new runtimeexception(t);     }   } 

see also:


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -