Question

I understand the concept of rescue- My question is this:

Should I write my begin rescue end code within my class or should I write it outside the class when I'm actually creating an object? If I have two files - one with my class, one where I call that class, which script do I put my rescue script in? Perhaps it doesn't matter, or maybe I should use both. Just wondering what best practices are for this...

Was it helpful?

Solution

The general rule with exception handling is to catch the exception at the lowest abstraction level where its possible to make an intelligent choice on how to handle the error.

If you can make an intelligent choice inside the class method, include your rescue logic there. If you will have more context at the caller level and you want custom logic each time the method is called, then put the rescue logic outside the class.

OTHER TIPS

Best practice is to put begin and rescue only around the specific piece of code you want to change default raise behaviour for (i.e. exit your code, potentially terminating the process unless there is a higher-level rescue), and to achieve the purpose you intended.

What that is varies according to why you need to begin...rescue clause in the first place.

For example, if your classes are a web service, and a component of that service, and the purpose of the block is to present all raised errors as debug stack-traces in the browser, then the outer, web-service layer is where you should rescue exceptions. You should probably also cover most, if not all, possible types of raised error.

Alternatively, if your "inner" class is providing access to a third-party service, and the rescue is to allow retries on a failed connect, the block could be entirely within the inner class. In addition, you would only rescue the specific failures where a retry would make sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top