Pwnna
Pwnna

Reputation: 9528

java throwing exception without catching it?

Is it possible to throw an exception without catching it?

Example

public void foo() throws SomeException{
    // ....
    if (somethingCatestrophic) throw new SomeException();
    // ....
}

Now I want to call foo, but don't want to catch any errors, as the exceptions should never been thrown at runtime (unless there's a bug)

Upvotes: 15

Views: 29005

Answers (5)

LSafer
LSafer

Reputation: 354

There is a trick, You can play with generics.

/**
 * A java syntax glitch to throw any throwable without the need to catch it.
 *
 * @param throwable to be ignite
 * @param <T>       the type of the throwable to trick the compiler that it's the one thrown
 * @throws T exactly the given throwable
 */
public static <T extends Throwable> void ignite(Throwable throwable) throws T {
    Objects.requireNonNull(throwable, "throwable");
    throw (T) throwable;
}

This test should pass

@Test(expected = IOException.class)
public void ignite() {
    ignite(new IOException());
}

Upvotes: 1

Boundless
Boundless

Reputation: 2464

You can avoid catching an exception, but if there is an exception thrown and you don't catch it your program will cease execution (crash).

There is no way to ignore an exception. If your app doesn't need to do anything in response to a given exception, then you would simply catch it, and then do nothing.

try {
  ...some code that throws an exception...
} catch (SomeException ex) {
  // do nothing
}

NOTE: This is often considered bad style, however, and people may tell you so. The often-cited reason is that, even if you're not going to do anything with the exception, that in most cases you should at least log it somewhere, notify the user, or take some other appropriate action depending on what you app is doing, and what caused the exception in the first place. If you're not sure why an exception is being thrown (maybe it's a bug you haven't solved yet), then generally you should at least log it so you can figure it out later.

Upvotes: 1

myro
myro

Reputation: 1196

Why don't you catch it inside the method?

Simply use try catch block and go on, if the exception is insignificant and doesn't influence any behaviour of your program.

Upvotes: 1

David H. Clements
David H. Clements

Reputation: 3638

Unless it is something you are planning for and recovering from locally, it is probably best in this case to use an unchecked exception, e.g., a RuntimeException derivative.

Upvotes: 39

Peter
Peter

Reputation: 6362

If SomeException is a checked exception, the method that calls foo() will either have to catch that exception and deal with it or also be declared to throw SomeException or a parent of it.

If SomeException is a runtime exception, then methods that call it will not need to catch it.

Upvotes: 0

Related Questions