Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching exceptions in Java

There are certain predefined exceptions in Java, which, if thrown, report that something serious has happened and you'd better improve your code, than catching them in a catch block (if I have understood it correctly). But still I find many programs in which I have the following:

} catch (IOException e) {
     ...
} catch (FileNotFoundException e) {
     ....
}

and I thought that IOException and FileNotFoundException are exactly such kind of exceptions, which we shouldn't catch in a catch block. Why people do this? Is it better to catch them like this? Java compiler warns anyway about any problem of that kind.

Thank you.

like image 260
user42155 Avatar asked Nov 28 '22 06:11

user42155


1 Answers

No, there's nothing wrong with catching IOException and FileNotFoundException - if you can genuinely handle those exceptions. That's the important bit - can you really proceed in the face of that exception? Sometimes you can - very often at the top level of a server, for example, where just because one request fails doesn't mean the next can't proceed. Less often in client apps, although it very much depends on the situation. Can't read a file when you're trying to do a batch import? Okay, abort the operation but don't necessarily shut down the whole process...

You shouldn't have them that way round, admittedly - the FileNotFoundException would be masked by the IOException which it derives from. Fortunately the compiler flat-out prevents you from doing this.

like image 190
Jon Skeet Avatar answered Dec 04 '22 21:12

Jon Skeet