Reputation: 718876
New Java programmers frequently encounter errors phrased like this:
"error: unreported exception <XXX>; must be caught or declared to be thrown"
where XXX is the name of some exception class.
Please explain:
Upvotes: 5
Views: 4859
Reputation: 718876
First things first. This a compilation error not a exception. You should see it at compile time.
If you see it in a runtime exception message, that's probably because you are running some code with compilation errors in it. Go back and fix the compilation errors. Then find and set the setting in your IDE that prevents it generating ".class" files for source code with compilation errors. (Save yourself future pain.)
The short answer to the question is:
The error message is saying that the statement with this error is throwing (or propagating) a checked exception, and the exception (the XXX
) is not being dealt with properly.
The solution is to deal with the exception by either:
try ... catch
statement, orthrows
it1.1 - There are some edge-cases where you can't do that. Read the rest of the answer!
In Java, exceptions are represented by classes that descend from the java.lang.Throwable
class. Exceptions are divided into two categories:
Throwable
, and Exception
and its subclasses, apart from RuntimeException
and its subclasses.Error
and its subclasses, and RuntimeException
and its subclasses.(In the above, "subclasses" includes by direct and indirect subclasses.)
The distinction between checked and unchecked exceptions is that checked exceptions must be "dealt with" within the enclosing method or constructor that they occur, but unchecked exceptions need not be dealt with.
(Q: How do you know if an exception is checked or not? A: Find the javadoc for the exception's class, and look at its parent classes.)
From the Java language perspective, there are two ways to deal with an exception that will "satisfy" the compiler:
You can catch the exception in a try ... catch
statement. For example:
public void doThings() {
try {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
} catch (IOException ex) {
// deal with it <<<=== HERE
}
}
In the above, we put the statement that throws the (checked) IOException
in the body of the try
. Then we wrote a catch
clause to catch the exception. (We could catch a superclass of IOException
... but in this case that would be Exception
and catching Exception
is a bad idea.)
You can declare that the enclosing method or constructor throws
the exception
public void doThings() throws IOException {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
}
In the above we have declared that doThings()
throws IOException
. That means that any code that calls the doThings()
method has to deal with the exception. In short, we are passing the problem of dealing with the exception to the caller.
Which of these things is the correct thing to do?
It depends on the context. However, a general principle is that you should deal with exceptions at a level in the code where you are able to deal with them appropriately. And that in turn depends on what the exception handling code is going to do (at HERE
). Can it recover? Can it abandon the current request? Should it halt the application?
To recap. The compilation error means that:
Your solution process should be:
Consider the following example from this Q&A
public class Main {
static void t() throws IllegalAccessException {
try {
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args){
t();
System.out.println("hello");
}
}
If you have been following what we have said so far, you will realise that the t()
will give the "unreported exception" compilation error. In this case, the mistake is that t
has been declared as throws IllegalAccessException
. In fact the exception does not propagate, because it has been caught within the method that threw it.
The fix in this example will be to remove the throws IllegalAccessException
.
The mini-lesson here is that throws IllegalAccessException
is the method saying that the caller should expect the exception to propagate. It doesn't actually mean that it will propagate. And the flip-side is that if you don't expect the exception to propagate (e.g. because it wasn't thrown, or because it was caught and not rethrown) then the method's signature shouldn't say it is thrown!
There are a couple of things that you should avoid doing:
Don't catch Exception
(or Throwable
) as a short cut for catching a list of exceptions. If you do that, you are liable catch things that you don't expect (like an unchecked NullPointerException
) and then attempt to recover when you shouldn't.
Don't declare a method as throws Exception
. That forces the called to deal with (potentially) any checked exception ... which is a nightmare.
Don't squash exceptions. For example
try {
...
} catch (NullPointerException ex) {
// It never happens ... ignoring this
}
If you squash exceptions, you are liable to make the runtime errors that triggered them much harder to diagnose. You are destroying the evidence.
Note: just believing that the exception never happens (per the comment) doesn't necessarily make it a fact.
There some situations where dealing with checked exceptions is a problem. One particular case is checked exceptions in static
initializers. For example:
private static final FileInputStream input = new FileInputStream("foo.txt");
The FileInputStream
is declared as throws FileNotFoundException
... which is a checked exception. But since the above is a field declaration, the syntax of the Java language, won't let us put the declaration inside a try
... catch
. And there is no appropriate (enclosing) method or constructor ... because this code is run when the class is initialized.
One solution is to use a static
block; for example:
private static final FileInputStream input;
static {
FileInputStream temp = null;
try {
temp = new FileInputStream("foo.txt");
} catch (FileNotFoundException ex) {
// log the error rather than squashing it
}
input = temp; // Note that we need a single point of assignment to 'input'
}
(There are better ways to handle the above scenario in practical code, but that's not the point of this example.)
As noted above, you can catch exceptions in static blocks. But what we didn't mention is that you must catch checked exceptions within the block. There is no enclosing context for a static block where checked exceptions could be caught.
A lambda expression (typically) should not throw an unchecked exception. This is not a restriction on lambdas per se. Rather it is a consequence of the function interface that is used for the argument where you are supplying the argument. Unless the function declares a checked exception, the lambda cannot throw one. For example:
List<Path> paths = ...
try {
paths.forEach(p -> Files.delete(p));
} catch (IOException ex) {
// log it ...
}
Even though we appear to have caught IOException
, the compiler will complain that:
catch
is catching an exception that is never thrown!In fact, the exception needs to be caught in the lambda itself:
List<Path> paths = ...
paths.forEach(p -> {
try {
Files.delete(p);
} catch (IOException ex) {
// log it ...
}
}
);
(The astute reader will notice that the two versions behave differently in the case that a delete
throws an exception ...)
I have seen cases where a method has a throws Xyzzy
clause, and the compiler still complains that Xyzzy
must be "caught or declared to be thrown". For example: Unreported exception ...... must be caught or declared to be thrown; despite *thrown* keyword.
If you find yourself in this situation, look carefully at the fully qualified names of the exceptions. If the fully qualified names are different, then the exceptions are different. (Believe what the compiler is saying and try to understand it.)
The Oracle Java Tutorial:
Upvotes: 9