It is common to wrap a checked exception with a RuntimeException for cases where a checked exception is fatal, or not actually possible. In order to reduce the number of stack trace “caused by” clauses, and to save on binary size, use JavaUtils.throwUnchecked()
instead.
try { somethingThatThrowsIOException(); } catch (IOException e) { // Bad - RuntimeException adds no context and creates longer stack traces. throw new RuntimeException(e); // Good - Original exception is preserved. throw JavaUtils.throwUnchecked(e); }
--
You received this message because you are subscribed to the Google Groups "java" group.
To unsubscribe from this group and stop receiving emails from it, send an email to java+uns...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/java/CABiQX1UjaFEjbzCYCwt-TXLZEcEiL_gVBtFu7kxGCdLBfB6hJA%40mail.gmail.com.
A quick primer:
Throwable
: Base class for all exceptionsError
: Base class for exceptions which are meant to crash the app.Exception
: Base class for exceptions that make sense the catch
.RuntimeException
: Base class for exceptions that do not need to be declared as throws
(“unchecked exceptions”).Use catch statements that do not catch exceptions they are not meant to.
catch (Throwable t)
, since that includes the (generally unrecoverable) Error
types.Use catch (Exception e)
when working with OS APIs that might throw (assuming the program can recover from them).
IllegalStateException
/ IllegalArgumentException
/ SecurityException
being thrown where only RemoteException
was being caught. If the program can recover from failed binder calls,Do not use catch (RuntimeException e)
.
RuntimeException
to make unchecked exception types, but the type does not make much sense in catch
clauses, as there are not times when you'd want to catch all unchecked exceptions, but not also want to catch all checked exceptions.Avoid adding messages to exceptions that do not aid in debugging. For example:
try { somethingThatThrowsIOException(); } catch (IOException e) {
// Bad - message does not tell you more than the stack trace does: throw new RuntimeException("Failed to parse a file.", e); // Good - conveys that this block failed along with the "caused by" exception. throw new RuntimeException(e); // Good - adds useful information. throw new RuntimeException(String.format("Failed to parse %s", fileName), e); }
It is common to wrap a checked exception with a RuntimeException for cases where a checked exception is not recoverable, or not possible. In order to reduce the number of stack trace “caused by” clauses, and to save on binary size, use JavaUtils.throwUnchecked()
instead.
try { somethingThatThrowsIOException(); } catch (IOException e) { // Bad - RuntimeException adds no context and creates longer stack traces. throw new RuntimeException(e); // Good - Original exception is preserved. throw JavaUtils.throwUnchecked(e); }