Question

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.

Was it helpful?

Solution

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top