0

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?

4
  • Can you show us the expected output and actual output? Commented Jul 6, 2017 at 16:10
  • 3
    IOException is a checked exception. The compiler doesn't know that your call to exep.second() won't throw one, so your code doesn't compile. Commented Jul 6, 2017 at 16:10
  • @byrox I was learning Exception handling and i just wanted to print "device error" when the exception is caught. Commented Jul 6, 2017 at 16:16
  • @jsheeran or because i threw the exception from second()? Commented Jul 6, 2017 at 16:17

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.