user1779715
user1779715

Reputation:

Is it possible to ignore an exception?

In Java, is it possible to make a method that has a throws statement to be not checked.

For example:

public class TestClass {
    public static void throwAnException() throws Exception {
        throw new Exception();
    }
    public static void makeNullPointer() {
        Object o = null;
        o.equals(0);//NullPointerException
    }
    public static void exceptionTest() {
        makeNullPointer(); //The compiler allows me not to check this
        throwAnException(); //I'm forced to handle the exception, but I don't want to
    }
}

Upvotes: 30

Views: 42783

Answers (10)

Bailey Ridley
Bailey Ridley

Reputation: 19

You can use a loophole in the Java Compiler. Add the following code:

public RuntimeException hideThrow(Throwable e) {
    if (e == null)
        throw new NullPointerException("e");
    this.<RuntimeException>hideThrow0(e);
    return null;
}

@SuppressWarnings("unchecked")
private <GenericThrowable extends Throwable> void hideThrow0(Throwable e) throws GenericThrowable {
    throw (GenericThrowable) e;
}

You can catch the exception, then invoke hideThrow with the exception to throw it without the compiler noticing. This works because of type erasure. At compile time, GenericThrowable represents RuntimeException because that is what we are passing. At run time, GenericThrowable represents Throwable because that is the basic type in the type parameter specification.

Upvotes: 1

JCalcines
JCalcines

Reputation: 1286

It is not advisable to avoid an exception with an empty catch block even though you are completely sure that is not going to fail under any circumstance. Sometimes, we are not aware of the human factor.

If you are sure that an exception is very unlikely to happen (if not impossible) you should create your own Exception and and wrap the unexpected exception in it.

For example:

private class UnlikelyException extends RuntimeException {
    public UnlikelyException (Exception e){
        super (e);
    }
}

Then wrap your code with a try-catch block and throw your exception, which you don't have to catch

try {
    // Your code
} catch  (Exception e) {
    throw new UnlikelyException(e);
}

Upvotes: 2

acdcjunior
acdcjunior

Reputation: 135762

You can try and do nothing about it:

public static void exceptionTest() {
    makeNullPointer(); //The compiler allows me not to check this
    try {
        throwAnException(); //I'm forced to handle the exception, but I don't want to
    } catch (Exception e) { /* do nothing */ }
}

Bear in mind, in real life this is extemely ill-advised. That can hide an error and keep you searching for dogs a whole week while the problem was really a cat(ch). (Come on, put at least a System.err.println() there - Logging is the best practice here, as suggested by @BaileyS.)

Unchecked exceptions in Java extend the RuntimeException class. Throwing them will not demand a catch from their clients:

// notice there's no "throws RuntimeException" at the signature of this method
public static void someMethodThatThrowsRuntimeException() /* no need for throws here */ {
    throw new RuntimeException();
}

Classes that extend RuntimeException won't require a throws declaration as well.

And a word from Oracle about it:

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Upvotes: 57

Stony
Stony

Reputation: 3624

AS I know, it's impossible in the case. Only unchecked exception, compiler can skip to check. such as RuntimeException.

Upvotes: 1

Salah Eddine Taouririt
Salah Eddine Taouririt

Reputation: 26415

In Java there is two kinds of Exceptions, Checked Exceptions and Unchecked Exceptions.

  • Exception is a checked exception, must caught or thrown.
  • NullPointerException is a RuntimeException, (the compiler doesn’t forces them to be declared in the throws claus) you can ignore it, ,but it still may occur in the Runtime, and your application will crash.

From Exception documentation:

The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

From the RuntimeException documentation:

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

Upvotes: 3

Rahul Saksule
Rahul Saksule

Reputation: 417

Just catch an exception and dont do any thing with it, leave it as it is and catch the generic exception in case you are not aware of the specific exception

try{
//Your logic goes here
}
catch(Exception e)//Exception is generic
{
//do nothing
}

Upvotes: 1

ruakh
ruakh

Reputation: 183290

The other answers are right, in that they correctly tell you what you should do, but it is actually possible to throw a undeclared checked exception. There are a few ways this can be done; the simplest is:

public void methodThatSecretlyThrowsAnException() {
    Thread.currentThread().stop(new Exception());
}

or if your goal is to wrap an existing method that does declare its exception

public void methodThatSecretlyThrowsAnException() {
    try {
        methodThatAdmitsItThrowsAnException();
    } catch(final Exception e) {
        Thread.currentThread().stop(e);
    }
}

(Needless to say, you should never do this.)

Upvotes: 1

Florent Bayle
Florent Bayle

Reputation: 11910

There are 3 things you can do :

  • Throw a RuntimeException (or something extending a RuntimeException, like NullPointerException, IllegalArgumentException,...), you don't have to catch these as they are unchecked exceptions.

  • Catch the exception and do nothing (not recommended) :

    public static void exceptionTest() {
        makeNullPointer(); //The compiler allows me not to check this
        try {
            throwAnException(); //I'm forced to handle the exception, but I don't want to
        } catch (Exception e) {
            // Do nothing
        }
    }
    
  • Change exceptionTest () declaration to say that it throws an Exception, and let the method calling it catch the Exception and do what is appropriate :

    public static void exceptionTest() throws Exception {
        makeNullPointer(); //The compiler allows me not to check this
        throwAnException(); //I'm no more forced to handle the exception
    }
    

Upvotes: 5

user93353
user93353

Reputation: 14039

Throw a RuntimeException or an exception which is derived from RuntimeException. Then the compiler will not force you to catch it.

Upvotes: 2

LexLythius
LexLythius

Reputation: 1944

No, it raises a compiler error. Being a checked exception, you must either catch it or propagate it by declaring your method as potentially throwing it. Check this and this.

Upvotes: 3

Related Questions