Reputation: 67283
So it is said to catch only exceptions which you cannot predict or are exceptional.
So for example, IOExceptions instead of FileNotFoundException (As this single case can be handled with a simple file check ot avoid using exceptions as flow control).
This is my understanding of the topic, correct me if I am wrong.
However, this raises the question....why are exceptions like FileNotFoundException available?
Thanks
Upvotes: 3
Views: 595
Reputation: 74949
You have to differentiate between best practices and absolute requirements. It's a best practice to check for the file first before trying to access it. However, that can't really be enforced. Since it's an absolute requirement that the file exist before it's accessed, the framework will throw an exception to enforce this condition.
In an ideal world, there would be no exception because there would be no bugs and all programs and networks (and users!) would be absolutely perfect.
Upvotes: 0
Reputation: 3952
You should catch exceptions that you can handle. Your first sentence is a little off and might be what is causing your confusion.
"So it is said to catch only exceptions which you cannot predict or are exceptional."
This should read
"So it is said to only throw exceptions in situations which you cannot predict or are exceptional."
Thus, if you can handle a FileNotFoundException, then you should catch it. There are a slew of exceptions that extend IOException and, surely, you cannot (would not want to?) handle all of them.
Upvotes: 2
Reputation: 39520
Consider the case where the file gets deleted on the filesystem between when you check for it and perform the operation that can cause the exception. This may seem unlikely, but this sort of thing DOES happen.
Upvotes: 2