Capture and control flow
Exceptions are simply, just packaged objects that contain error information. These are typically meant for more exceptional cases that require halting the current program flow to handle abnormal conditions. This is different from else
clauses, error codes or state variables which are more about guiding the control flow.
They also allow you to clearly segregate the expected processing of your workflow from the anticipated exceptional cases in your code
This is exactly what we want. It does a few important things.
Our code is neatly segregated from the part where the exception is handled. The exception is handled after the rescue
clause and everything before that in the begin
block is code that has problems that we can anticipate.
In this next example, we call the backtrace
method on the error
variable, which is an instance of the SyntaxError
class. This variable allows us to go through the current call stack of your program.
Another important thing it allows us to do is halt execution. Notice how it exits the block after the second eval
line raises an exception. Nothing else is executed after it.
This is one of the differences between raising error codes and raising exceptions. Exceptions preempt the usual workflow, error codes are more passive, and explicitly need to be handled later on in your program.
Here's what an error code handling flow might look like, handlingzen?
that returns 200
in the if
block sometime after.
Exception
class.