1

here is a code:

try {
    FileOutputStream fout=new FileOutputStream("path");
    javaClassFun(url,fout);
    fout.close();
} catch (MalformedURLException ex) {
    System.err.println("Invalid URL"+ex);
} catch (IOException e) {
    System.err.println("Input/Output error"+e);
}

when i cut the last catch block and paste it after try block it gives unreachable catch block error. I want to know what is the reason behind this.

1
  • When an Exception is thrown, the catch block checks whether the thrown exception is an instance of Exception type in catch block and leaves it inside catch block. In your case, the catch block with IOException swallow all IOException and its subtypes. i.e. MalformedUrlException Commented Feb 22, 2014 at 15:58

1 Answer 1

9

The reason why is that MalformedURLException inherits from IOException.

try {
    //call some methods that throw IOException's
} catch (IOException e) {
    // This will catch MalformedURLException since it is an IOException
} catch (MalformedURLExceptionn ex) {
    // Will now never be caught! Ah!
}

If you want to design catch blocks which properly handle an exception hierarchy, you need to put the super class last and the subclasses which you want to handle individually prior to it. See the example below for how to handle the IOException class hierarchy as it pertains to your code.

try {
    //call some methods that throw IOException's
} catch (MalformedURLExceptionn ex) {
    // This will catch MalformedURLException 
} catch (IOException e) {
    // This will catch IOException and all other subclasses besides MalformedURLException
}
Sign up to request clarification or add additional context in comments.

2 Comments

You should probably explain what that means, and why it produces the behavior that OP is seeing.
@HunterMcMillen: Updated with an explanation and solution to the problem that the OP is seeing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.