Reputation: 136
When a method throws an exception, it searches through the call stack to find a handler right? In that sense, why is there an error with exep.second();? even though i've caught the exception in method second(). Here's my code:
public class Exep {
void first()throws IOException{
throw new IOException("device error");
}
void second()throws IOException{
try{
first();
}catch(Exception e){
System.out.println(e);
}
}
public static void main(String args[]){
Exep exep = new Exep();
exep.second();
}
}
But the error disappears on adding throws IOException to the main(). Why?
Upvotes: 0
Views: 106
Reputation: 566
IOException is a checked exception, and so must be handled in some way. Adding throws IOException
to main suppresses this behavior, but it is not good practice.
In second()
, you catch all exceptions from first()
, but you still include the throws IOException
in the declaration of second()
. This is not necessary, because you can guarantee that any exception thrown by first()
will be caught and handled in second()
.
For more reading: Exceptions
Upvotes: 2
Reputation: 5342
You are telling the compiler that second()
throws IOException, but when you call second()
you aren't wrapping it in a try/catch block. If you want to leave it as is then you need to include a try catch block inside your main.
However, as you have it, you're never throwing an exception from inside of second()
so you can remove the line throws IOException
from there.
Upvotes: 1
Reputation: 15241
You explicitly declared that method second()
throws an exception. Compiler is unaware that exception is actually being caught within a method. Move the catch
part into main()
and the error will disappear. Or even better, remove the throws
statement since you are not throwing anything.
Upvotes: 1
Reputation: 130
If you declare void second() throws IOException
and then you call the method in main, you need to catch the exception this method may throw, just like you did with the first()
method. In that case you simply don't need the throws
clause in second()
.
Upvotes: 1