In Java, what is the difference between catch a generic exception and a specific exception (eg. IOException?)

The difference between performing a general try/catch statement and catching a specific exception (e.g. a FileNotFoundException) typically depend on what errors you need to handle and what errors you don’t need to worry about. For instance:

catch (Exception e) {    //A (too) general exception handler
...
}

The code above will catch EVERY exception that is thrown inside of the try statement. But maybe you don’t want to handle every error. What can you do with an “OutOfMemory” exception?

A better method of error handling would be to perform some default action if the error is unknown or something you can’t do anything about, and perform another action if you discover that you can do “Plan B” if you catch.

For example, assume you are trying to open a file, but the file doesn’t exist. You can catch the FileNotFoundException and create a new blank file as below:

catch (FileNotFoundException e) {    //A specific exception handler
    //create a new file and proceed, instead of throwing the error to the user
}catch (Exception e) {    //For all other errors, alert the user
    ...
}

This has been the most effective and user-friendly method of error checking that I’ve used in the past.

Leave a Comment