java - How do I use Throwables.propagateIfInstanceOf() from Google Guava? -
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
Post a Comment