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 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
}
2
  • 4
    You should probably explain what that means, and why it produces the behavior that OP is seeing. Feb 22, 2014 at 15:52
  • @HunterMcMillen: Updated with an explanation and solution to the problem that the OP is seeing.
    – Derek W
    Feb 22, 2014 at 16:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.