Is there a way to throw an exception without adding the throws declaration?
I have the following situation.
I have a Java Class that inherits from another base class and overrides a method.
The base method does not throw exceptions and thus has no throws ...
declaration.
Now my own method should be able to throw exception but I have the choices to either
- Swallow the exception or
- Add a throws declaration
Both a not satisfying because the first one would silently ignore the exception (ok I could perform some logging) and the second would generate compiler errors because of the different method headers.
public class ChildClass extends BaseClass {
@Override
public void SomeMethod() {
throw new Exception("Something went wrong");
}
}
Solution 1:
You can throw unchecked exceptions without having to declare them if you really want to. Unchecked exceptions extend RuntimeException
. Throwables that extend Error
are also unchecked, but should only be used for completely un-handleable issues (such as invalid bytecode or out of memory).
As a specific case, Java 8 added UncheckedIOException
for wrapping and rethrowing IOException
.
Solution 2:
Here is a trick:
class Utils
{
@SuppressWarnings("unchecked")
private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
{
throw (T) exception;
}
public static void throwException(Throwable exception)
{
Utils.<RuntimeException>throwException(exception, null);
}
}
public class Test
{
public static void main(String[] args)
{
Utils.throwException(new Exception("This is an exception!"));
}
}
Solution 3:
A third option is to opt out of exception checking (just like the Standard API itself has to do sometimes) and wrap the checked exception in a RuntimeException
:
throw new RuntimeException(originalException);
You may want to use a more specific subclass of RuntimeException
.