I agree that checking for errors that don't open the directory isn't fun. I think my comment needs some more explanation though.
There are only two situations where you should use "open or die". The first is in an academic setting where you are learning the language, sitting at your terminal, and can see when you code exits early and then fix the problem.
The other situation where "open or die" is the correct thing to do is when you have written a script for yourself, are sitting at your terminal when you run it, and can address anything that causes it to exit early.
There are, however, a plethora of situations where "open or die" is definitely not the right thing to do:
- When you have written the script for someone else to run, but they are not a programmer. They are just running the script.
- When you have the script running as a cron job.
- When the script is an application on a website processing data input by users.
- When the script is part of a larger application, especially in an SaaS kind of setting.
- Probably more but they would just get repetitive.
In these settings you don't want to use "open or die" because any good data that comes after the bad data doesn't get processed. Had I been hired to write the script above, I would have added an ELSE statement to the "if open" so that I could capture/log the input that failed to open. That way it could be reported, investigated, and corrected.
In a website/service setting, the "open or die" is not good because it would exit in-elegantly, giving the user a 500 error. Something of no use to anyone except the programmer. What you want is a structure where the error does not crash the program, but rather reports the bad data and keeps processing OR exits in an elegant fashion by telling the user what went wrong and who to contact to fix it. The "open or die" definitely will not do that because the end user doesn't get to see the error logs.
As I said, there are times when "open or die" is the right choice, but it is never the right choice when compared to the needs of the end client/user who is expecting a result, not an error. In a commercial script (one you are hired to write for someone else), you need to always put the client/user first. "or die" does not do that. Using an "if-else" that will handle the exception elegantly does do that.
In the OP's situation, he has already been running his data for some time, so he has already validated it. That was why I didn't bother with the "die" or an "else" statement. Had I been hired to write a script to process it, I would have included the else statement to capture the bad data and report it to him so he didn't have to go figuring out what it was. I would have put his needs above my needs.
I hope that people will think more on the "or die" and when they are implementing it. It serves a purpose, but it's not always the best way to handle an exception.
|