views:

51

answers:

1

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 every 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?

+2  A: 

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.

Matchu
Letting it float up doesn't make sense for me because I'm not writing a library. The errors have already floated up in my case, unless I'm seriously misunderstanding how exception-handling works in Ruby (quite possible). The issue is that errors stop scripts when I'd rather they keep running and I can simply check the errors in a logfile later or something.
ehsanul
@ehsanul - it only makes sense to keep running if you know it's okay to keep running. Swallowing all errors is a very dangerous behavior, especially if the exception is indicative of a critical issue that would cause the system to be damaged if you proceed. But when you know that the issue is only temporary and likely only applies to one isolated task, that's different... but it's extremely situational, and each individual exception must be handled individually :/
Matchu