It seems like I have begin ... rescue ... end
statements everywhere in my code! This doesn't seem like the correct thing to do.
Can anyone suggest how I can catch any exceptions without having to place everything inside begin ... rescue ... end
? Any way to just tell Ruby to shut up and just keep going even if an exception is raised?
As in other languages, for any non-trivial program, you actually need a well-thought-out architecture for processing exceptions. One approach is to define exception-handling scopes within your project, and then you typically want to catch (rescue) exceptions at the scope boundaries. There is a trade-off. The closer you are in the stack to where the exception occurred, the more contextual information you have about the condition that triggered it. If you try to be too granular, you run into the problems that you have described. On the other hand, if you only catch exceptions at the top of the stack (in "main"), then there is no context. So defining the exception-handling scopes involves evaluating that tradeoff in relation to your particular program or system.
Ruby gives us the ability to "retry" -- not available in some other languages. This should be used sparingly! But where it makes sense (e.g. waiting for the network or a resource to be freed), such exceptions need to be handled very locally.
Otherwise, I tend to define exception scopes at a fairly coarse-grained level on a large project. It is often useful to capture some contextual information as the exception bubbles up from the point of origination through the various exception scope boundaries. To help with this, you can extend the Ruby exception class hierarchy by defining some of your own application-specific exception types, but again there are trade-offs. Your project should have clear standards about when to use custom exception types vs. capturing contextual data in the message field, what kind of information the message field should contain, etc., and a strategy for cataloguing the messages that your code can generate.
In most cases, exceptions can be allowed to propagate upward to a centralized handler, to be logged (for the technical team and support), to generate useful error messages for the user, and to determine whether the condition is serious enough to require your program to exit. Generally, all exceptions should be handled within your code or within the application framework you are using. No exceptions should be allowed to escape to the default exception handling of the language runtime or the OS.
Those are my thoughts based mostly on experience with other languages, but I think they apply pretty generally. Bottom line, on a large project you need to put quite a lot of effort into designing exception handling, vs. an ad hoc approach.
def action
yield
rescue
....
ensure
....
end
action { stuff_goes_here }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With