94

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");
        }
}
sanjeevRm
  • 1,541
  • 2
  • 13
  • 24
Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189

12 Answers12

113

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.

OrangeDog
  • 36,653
  • 12
  • 122
  • 207
45

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!"));
    }
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • I wonder how does this work? I will do some research, but do you have any resources, which may help me? :-) – holmicz Nov 22 '16 at 08:24
  • 1
    T inferred as RuntimeException. Answered here http://stackoverflow.com/questions/41380656/how-java-e-extends-throwable-become-unchecked-exception and here http://stackoverflow.com/questions/31316581/a-peculiar-feature-of-exception-type-inference-in-java-8 – seenimurugan Dec 29 '16 at 13:43
  • 1
    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. – JasonMing Aug 29 '17 at 08:22
  • 1
    has the extra super added bonus of not having to deal with unsafe. – lscoughlin Mar 14 '20 at 09:51
  • Why do you need the dummy parameter ? Also, could this work without the generic method ? – Kiruahxh Aug 03 '20 at 07:22
34

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
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.

dogbane
  • 266,786
  • 75
  • 396
  • 414
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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Second method is interessting, too. But at the moment, wrapping the exception is excactly what I need. – Jürgen Steinblock Dec 23 '10 at 14:43
  • http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html – OrangeDog Dec 23 '10 at 14:45
  • @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. ;) – Peter Lawrey Dec 23 '10 at 15:56
  • "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? – Peter Lawrey Dec 23 '10 at 15:58
  • "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." – OrangeDog Dec 23 '10 at 21:34
  • @OrangeDog, That applies if you stop another thread in a random location, but if you "stop" the same thread, its not in a random location and is "behaviorally identical to Java's throw operation" i.e. its no more dangerous than throwing an unchecked exception or error. – Peter Lawrey Dec 23 '10 at 23:10
  • Aside from the fact that it is a horrible and unnecessary hack, any attempt to catch the exception will result in compiler warnings. Plus no-one using your code will be expecting it to throw checked exceptions without them being declared, making errors of omission highly likely. In the worst case, the compiler might optimise things away, assuming (reasonably) that checked exceptions won't be thrown without declaration. Don't think that you know better than the language designers when they explicitly tell you not to do something. – OrangeDog Dec 24 '10 at 00:25
  • While this is all true, I can only conclude you don't think wrapping the exception is any better (as all your points apply to that approach as well) and have avoided answering this question. IMHO its worse as it obscures the original exception. BTW: The compiler does very little in the way of optimisations the JIT does 99% of them. – Peter Lawrey Dec 24 '10 at 09:20
  • @OrangeDog: What about the case where one needs to take note of any exception that occurs, regardless of its type, and then rethrow *that same exception*? If a methods called from a `try` block are declared as throwing a few different checked exceptions, catching and rethrowing `Exception` would be cleaner than catching and rethrowing each individual exception the inner methods might throw, but unless one can "secretly" rethrow I don't know how to make the compiler tolerate a catch-and-rethrow of `Exception`. – supercat Dec 26 '13 at 20:36
  • I can think of no situation where you'd _need_ to do that. If you think you do, then there's probably something better you can be doing. – OrangeDog Dec 27 '13 at 21:15
  • @OrangeDog: Sometimes it is necessary for code in a `finally` block to know whether the `try` block succeeded (among other things, it may be appropriate to suppress an exception which occurs in the `finally` block if and only if the `try` block also threw an exception--a pattern used by Java itself in try-with-resources). The code to handle that should be agnostic to the type of exception involved; it sounds like as of Java 6 it can be. – supercat Dec 30 '13 at 20:46
3

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.

Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
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);
   }
}
Jason S
  • 184,598
  • 164
  • 608
  • 970
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.

dan1st
  • 12,568
  • 8
  • 34
  • 67
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

fmucar
  • 14,361
  • 2
  • 45
  • 50
0

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;
    }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
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);
        }
    }
}
-1

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

Erhan Bagdemir
  • 5,231
  • 6
  • 34
  • 40