Exceptional Exception Handlers



As a budding developer, I quickly discovered that there's nothing quite as satisfying as debugging a frustrating error after hacking away at it for what seems to be an eternity. But sometimes error messages aren't very clear and it can make the debugging process especially difficult.

Enter exception handlers!

Before we dive into just what an exception handler is and does, we need to take a look at a key question - what is an error and how are errors raised? 

In Ruby, an error is an instance of the predefined class Exception that is raised (or thrown) when something has gone wrong. By default, Ruby programs terminate when an exception occurs, unless you have an exception handler - a block of code that is executed when an exception occurs.



To handle exceptions, we can enclose the code that could throw an exception in a begin-end block and use one or more rescue clauses to tell Ruby the types of exceptions to handle. Note that the body of a method definition is an implicit begin-end block, and thus begin is usually omitted.

In the above example, the block will only execute up until line 5, then an error will be thrown when line 6 is hit when you realize you haven't put on your clothes.



To fix this, let's add an exception handler so we can get to work.

Now that we've added lines 7 through 8, which tells our program how to handle our exception on line 6, our program doesn't break so the method executes the remaining lines and we are able to get to work on time!


We can also use rescue clauses to print error messages without terminating. This can be done in the following way:



Using two built-in methods of the Exception class - message, which returns a string; and backtrace, which returns an array of strings that represent the call stack at the point that the exception was raised to provide human-readable details on what went wrong and where it went wrong.





Rescue clauses can also be stacked to handle different error types with a parameter. If no parameter is given, the parameter will default to StandardError.


Comments

Popular posts from this blog

Would you like an extra end with that? Curly Braces vs. Do End Blocks

Drag and Drop It Like It's Hot