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?
IOExceptionis a checked exception. The compiler doesn't know that your call toexep.second()won't throw one, so your code doesn't compile.