I have some code that might throw both checked and runtime exceptions.
I'd like to catch the checked exception and wrap it with a runtime exception. But if a RuntimeException is thrown, I don't have to wrap it as it's already a runtime exception.
The solution I have has a bit overhead and isn't "neat":
try { // some code that can throw both checked and runtime exception } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); }
Any idea for a more elegant way?
A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.
Because the Java programming language does not require methods to catch or to specify unchecked exceptions ( RuntimeException , Error , and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException .
I use a "blind" rethrow to pass up checked exceptions. I have used this for passing through the Streams API where I can't use lambdas which throw checked exceptions. e.g We have ThrowingXxxxx functional interfaces so the checked exception can be passed through.
This allows me to catch the checked exception in a caller naturally without needing to know a callee had to pass it through an interface which didn't allow checked exceptions.
try { // some code that can throw both checked and runtime exception } catch (Exception e) { throw rethrow(e); }
In a calling method I can declare the checked exception again.
public void loadFile(String file) throws IOException { // call method with rethrow }
/** * Cast a CheckedException as an unchecked one. * * @param throwable to cast * @param <T> the type of the Throwable * @return this method will never return a Throwable instance, it will just throw it. * @throws T the throwable as an unchecked throwable */ @SuppressWarnings("unchecked") public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T { throw (T) throwable; // rely on vacuous cast }
There is a lot of different options for handling exceptions. We use a few of them.
https://vanilla-java.github.io/2016/06/21/Reviewing-Exception-Handling.html
Guava's Throwables.propagate()
does exactly this:
try { // some code that can throw both checked and runtime exception } catch (Exception e) { throw Throwables.propagate(e); }
UPDATE: This method is now deprecated. See this page for a detailed explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With