I'm not asking about how to use the begin..rescue statement in Ruby. Rather, I'm asking how do you figure out what's worth worrying about. I know some hardcore people probably go through the documentation/code to find e开发者_高级运维very single possible error, and have code that handles all cases gracefully. But that might be going too far if you're not writing something "mission-critical".
So how do you know what errors to look out for? I generally just run my code, and if it stops due to an error, I add a begin..rescue statement. I'm sure there has to be a better way though. I just ran a script to import data into a database for some files, and it stopped after an hour (lots of files, don't ask) due to some error that I couldn't know was going to occur. Quite annoying, and I'm sure it's my fault for not writing more robust code. How do I do that?
I'm not sure it's always possible to always forsee exceptions without first experiencing them. Now that you know that databases sometimes fail, you might add better exception handling for that in the future, but experience is the only real teacher in this sense.
However, I think you might be a bit too quick to write your own error handlers. For production code, there are obviously certain scenarios you want to be able to catch easily and show a good error message for (e.g. too many database connections), but sometimes allowing the error to float up is, in fact, the most robust thing a script can do. If there's something wrong with my rubygems setup that causes your gem to spit up errors, I don't want you to hide them behind "something went wrong!"; I'd rather see the error itself so I can get down to work.
Catch the errors that really matter, and that you can do something about, like to retry a HTTP connection a few times before giving up. Beyond that, however, if there's nothing you can do about the error, there's no shame in letting it float up.
精彩评论