开发者

Catching exception on filenotfound

开发者 https://www.devze.com 2023-03-11 07:56 出处:网络
So it is said to catch only exceptions which you cannot predict or are exceptional. So for example, I开发者_如何转开发OExceptions instead of FileNotFoundException (As this single case can be handled

So it is said to catch only exceptions which you cannot predict or are exceptional.

So for example, I开发者_如何转开发OExceptions 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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消