29

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
    }
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614

10 Answers10

57

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.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • 6
    Very nice post. Another thing that I would suggest is to at least record the ignored exception in a logger. – le3th4x0rbot May 24 '13 at 02:41
  • 2
    I wanted to downvote this for the terrible pun, but I couldn't bring my self to do it. +1 for a good answer – Craig May 24 '13 at 02:42
  • 11
    @Craig Oh, come on, the pun brings the post to a whole new level :P – acdcjunior May 24 '13 at 02:42
  • 3
    This makes one wonder what they mean by "reasonably be expected to recover." From the perspective of the program itself, not much can be done if a file is missing, but `FileNotFoundException` is checked. The best the program can do is notify the user (assuming there's a way to get output to a user, which might not be the case for a scheduled service or what have you). If "notify the user of the error" is considered a "reasonable recovery", then programs can "reasonably be expected to recover" from literally any exception, making the `RuntimeException` useless. – jpmc26 May 24 '13 at 02:44
  • Log exceptions, but don't log them twice. I've seen too many systems where the same exception was logged multiple times because each method call catches, logs, and rethrows them. Handle them at the boundary between modules if there's no place else to handle them. – Eric Jablow May 24 '13 at 02:47
  • @jpmc26 You have a good point there. No wonder the title of that article from Oracle is [Unchecked Exceptions — The Controversy](http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html). I remember being at a C# where the first thing they did was bash Java's checked exception system... – acdcjunior May 24 '13 at 02:48
  • 5
    I think maybe this line does a better job of explaining the intended usage: "Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way." In other words, `RuntimeException`s are bonehead exceptions that come from when the programmer forgot to account for some case or programmed something wrong and the caller gave your code unusable data or objects to work with. They're a way of giving the caller a useful error message to give them a clue what they did wrong. – jpmc26 May 24 '13 at 02:55
  • The word from Oracle is against current best practices for interface programming and handling/converting exceptions with aspects. – Danubian Sailor May 24 '13 at 09:07
  • A slight improvement would be to only catch the exact checked exception that you want to ignore. Quite unnecessary to swallow *all* exceptions just to ignore a single one :) – Svish May 24 '13 at 10:31
  • 1
    If code calls a method which is declared as `throws` a checked exception, but expect that particular call will never actually throw the exception, the exception should be caught and rethrown as a non-checked exception type (e.g. `RuntimeException`). It should not be swallowed. The only time an exception should be swallowed without taking any action is when a method is *known to throw it in cases the application doesn't care about*; exceptions which are expected never to occur don't come even close to fitting that criterion. – supercat May 24 '13 at 15:00
  • Situations where method caller catches and ignores an exception are strongly indicative of defects in either the caller or the called method. In some cases, the defect may stem from the fact that a `DoSomething` method should, but doesn't, provide a `TryDoSomething` alternative. If the class or interface with that method is well-established, swallowing the exception, though ugly, may be the only practical way of dealing with the situation. – supercat May 24 '13 at 15:21
  • 1
    @jpmc26: Somewhere along the line, the not-found filename was almost certainly derived from input at runtime (a config file, user input, whatever). That's why it's checked; it's an error that can happen even when the program itself is running right. Of course, from the perspective of the *function*, not much can be done if the file doesn't exist...but the *caller* (or its caller, or...) has a larger view of the app and its intentions. I could reasonably catch `FileNotFoundException` and (for example) mention the config issue, use a fallback, or prompt the user to select an existing file. – cHao May 26 '13 at 14:43
  • 1
    I don't typically have those options with a `NullPointerException`. That's a lower-level exception; it basically says "the runtime won't let us do that", but doesn't provide (specific) enough info to reasonably recover. All you get is a stack trace, and that's rather useless to a user. – cHao May 26 '13 at 14:47
  • Does anyone happen to know wether threads are forced-stopped by some exceptions - even if you catch those errors? – Lealo Aug 11 '17 at 02:49
  • @Lealo I don't think they are, but it's been a while since I messed with those. I suggest you create a question of your own. It is very relevant. – acdcjunior Aug 11 '17 at 10:55
  • I am blocked from asking questions unfortunately. However I found out that all exceptions does stop the thread even if you catch them. But when you use your thread boolean flag in a while loop instead of just an if condition the thread runs once - but the while loop is started and keeps on going. So you need to switch from using if to a while condition. – Lealo Aug 11 '17 at 16:38
  • maybe closest thing is to `throw new RuntimeException(e)` although that may clear stack trace, i haven't tried that yet. – M.kazem Akhgary Nov 26 '18 at 19:54
4

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
    }
    
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
  • I would suggest that if a method is declared as throwing a checked exception, but a particular call is expected never to throw, one should catch the checked exception and wrap it in something like `RuntimeException`. Indeed, I would consider such behavior appropriate even if (perhaps *especially if*) the method making the call is expected to throw that exception in some different circumstance. If `LoadDocument(string filename)` throws `FileNotFoundException`, that should indicate that `filename` wasn't found--not that some other necessary file like a template wasn't available. – supercat May 24 '13 at 15:27
3

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.

LexLythius
  • 1,904
  • 1
  • 12
  • 20
  • I am not down voter, but your answer is bit incomplete, consider @tarrsalah , you may find answer – Grijesh Chauhan May 24 '13 at 07:30
  • 3
    Not the downvoter either, but it is also recommended to summarize the important points made in any references linked such that the answer can stand on its own even if the linked documents are moved or disappear. – user May 24 '13 at 09:32
3

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.

Salah Eddine Taouririt
  • 24,925
  • 20
  • 60
  • 96
  • 1
    Of course, if you ignore a `NullPointerException` (or any exception) (as opposed to catching it and throwing it away), your application will crash. – user May 24 '13 at 09:31
2

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

user93353
  • 13,733
  • 8
  • 60
  • 122
2

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);
}
jellyberg
  • 168
  • 4
  • 14
JCalcines
  • 1,236
  • 12
  • 25
2

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.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
1

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

Stony
  • 3,541
  • 3
  • 17
  • 23
  • This answer is self-contradictory. First you say it's impossible, then you explain (sort of) how it is possible. Which will it be? – user May 24 '13 at 09:33
  • I just updated my answer, it's impossible in the case (user's case). And then explain if user really want to throw an exception which can not be caught, we only can use unchecked exception. – Stony May 26 '13 at 14:21
1

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.)

ruakh
  • 175,680
  • 26
  • 273
  • 307
1

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
}
Rahul Saksule
  • 417
  • 5
  • 15