100

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"); } } 

12 Answers 12

118

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Works great, I have to rethrow a RuntimeException because the exception comes from another method but it works great, thanks.
49

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!")); } } 

5 Comments

I wonder how does this work? I will do some research, but do you have any resources, which may help me? :-)
T inferred as RuntimeException. Answered here stackoverflow.com/questions/41380656/… and here stackoverflow.com/questions/31316581/…
Awesome trick! This trick can also apply on lambda expression/block, to allow assigning the checked-exception method to the SAM interface without any throws declarations.
has the extra super added bonus of not having to deal with unsafe.
Why do you need the dummy parameter ? Also, could this work without the generic method ?
36

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.

Comments

10

I just want do add an alternative answer, purely as an FYI:

Yes, there is a way to throw a checked exception without adding the throws declaration, by using the sun.misc.Unsafe class. This is described in the following blog post:

Throw a checked exception from a method without declaring it

Sample code:

public void someMethod() { //throw a checked exception without adding a "throws" getUnsafe().throwException(new IOException()); } private Unsafe getUnsafe() { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); return (Unsafe) field.get(null); } catch (Exception e) { throw new RuntimeException(e); } } 

However, this is not recommended. It is better to wrap in an unchecked exception as outlined in the some of the other answers.

1 Comment

There's a reason they call that class Unsafe.
5

Why don't you throw an unchecked exception? This doesn't have to be declared.

Two alternatives are

  • wrap with a checked exception with an unchecked one.
  • don't let the compiler know you are throwing a checked exception e.g. Thread.currentThread().stop(e);
  • In Java 6, you can rethrow the exception if it is final and the compiler know which checked exceptions you might have caught.
  • In Java 7, you can rethrow an exception if it is effectively final, i.e. you don't change it in code.

The later is more useful when you are throwing a check exception in you code and catching it in your calling code, but the layers inbetween don't know anything about the exception.

11 Comments

Second method is interessting, too. But at the moment, wrapping the exception is excactly what I need.
@OrangeDog, since you have read this, can you tell me what is the difference between using stop() on the current thread and throwing a wrapped exception. ;)
"the following method is behaviorally identical to Java's throw operation, but circumvents the compiler's attempts to guarantee that the calling method has declared all of the checked exceptions that it may throw" how is wrapping the exception any better?
"Stopping a thread causes it to unlock all the monitors that it has locked. If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. [...] Unlike other unchecked exceptions [...] the user has no warning that his program may be corrupted."
|
4

Yes there is a why but it is not recommended at all you can use :

Java unsafe package

getUnsafe().throwException(new IOException()); 

This method throws checked exception, but your code not forced to catch or rethrow it. Just like runtime exception.

Comments

2

Here's an example for intercepting checked exceptions and wrapping them in an unchecked exception:

public void someMethod() { try { doEvil(); } catch (IOException e) { throw new RuntimeException(e); } } 

Comments

2

If you use Project lombok and want to throw checked exceptions without the throws declaration, you can add @SneakyThrows to the method:

public void yourCaller(){ yourMethod(); } @SneakyThrows public void yourMethod(){ throw new Exception("Something went wrong"); } 

This can throw checked exceptions without the caller needing to catch them.

Lombok provides an annotation processor that modifies the code at compile-time. With @SneakyThrows, it catches and re-throws the exception without the throws declaration.

As described in the description of @SneakyThrows, it transforms code into something like that:

public void yourMethod() { try { throw new Exception("Something went wrong"); } catch (Exception t) { throw Lombok.sneakyThrow(t); } } 

From the sources of Lombok.sneakyThrow():

public static RuntimeException sneakyThrow(Throwable t) { if (t == null) throw new NullPointerException("t"); return Lombok.<RuntimeException>sneakyThrow0(t); } @SuppressWarnings("unchecked") private static <T extends Throwable> T sneakyThrow0(Throwable t) throws T { throw (T)t; } 

As you can see, it uses generics to trick Java into thinking that this would be an unchecked exception as shown in this answer.

Comments

1

In Java 8, throwing a checked exception without declaring it can be done more easily due to type inference.

public class Main { public static void main(String[] args) { throwException(new Exception("exception")); } public static <T extends Throwable> void throwException(Throwable t) throws T { throw (T) t; } } 

2 Comments

Thanks, but already posted here stackoverflow.com/a/18408831/98491
@JürgenSteinblock That is not the same method; it requires a helper method while my answer does not.
0

You can use any exception derived from RuntimeException or RuntimeException itself

or

use a try-block for the exception throwing code and handle it there

Comments

0

Yes there is, using typecast to Runtime exception and throws a runtime exception.

Create an Exception helper class like this.

public class ExceptionHelper { public static <T> void throwException(Throwable t) throws Throwable { throw (Throwable) t; } } 
class ServiceClass { public void actualFlow() { try { //somethinf } catch (Exception e) { ExceptionHelper.throwException(e); } } } 

Comments

-1

you can catch the exception with try- catch block in your method overridden. then you don't need to declare throws- statement.

1 Comment

sure, but then I would swallow the exception, which is exactly the opposite of what I want to achive ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.