3 ms·
FileNotFoundException is not really a corner case, it's all but unavoidable race. No matter how soon you open the file after verifying its existence, it could h
by barrkel 17y ago
FileNotFoundException is not really a corner case, it's all but unavoidable race. No matter how soon you open the file after verifying its existence, it could have gone away. And the only reasonable thing you can do in the face of it is route the message that the file is missing to the user one way or another, and possibly exit.
In that way, it makes sense for a top-level handler, such as at the main() routine or in the event loop in a GUI app, to be the one to handle it, and for all intermediates to pass it up. The fact that most meaningful applications do I/O at some level, means that almost the only routines that can be indicated not to throw this exception or a similar I/O exception, are functionally pure ones, or the ones that implement the aforementioned user notification.
- gnaritas 17y agoWhy would you verify it's existence? Just open it, you either get it or you don't. If you don't then catch the exception and do what you would have done if you'd have checked and it wasn't there. Honest question?
- mkinsella 17y agoOpening a file (or attempting to) is resource intensive and throwing/catching exceptions is sloooow.
- swolchok 17y agoBoth opening the file and checking whether it exists involve a syscall, which dwarfs the overhead of throwing and catching an exception. If you check whether it exists and then try to open it, that's two syscalls.
- swolchok 17y agoOn reflection, it occurs to me that a Sufficiently Smart Compiler (TM) could figure out that you were going to open the file right after checking whether it exists and just call open(2) as the existence check instead of stat(2) and then open(2). This seems to depend on the details of the library implementation as well, though.
- Confusion 17y agoI don't know how many files you open in your applications, but in all of mine, the number is so small that I could not care less about the overhead of an exception.
- eru 17y agoThe slowness of exceptions depends on your language / implementation of you language.
- gnaritas 17y ago> and throwing/catching exceptions is sloooow. That's not seeing the forest for the trees. Unless a specific inner loop of the program shows up in a profiler as the hotspot because of an exception, this just isn't something you should ever worry about in 99% of code. Don't throw out the nice abstractions that make code simple unless you know for sure it's the actual problem, rarely is that the case for throwing exceptions. In this particular instance, I'd say you're just wrong about not using an exception.