Recover in Crystal
Crystal makes it possible to recover from a panic, using the begin
/rescue
construct. This can stop a panic from aborting the program and let it continue with execution instead.
An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients.
# This function raises an exception.
def may_raise
raise "a problem"
end
# The rescue block must be within the same scope as the code that might raise.
# When the enclosing function raises an exception, the rescue block will
# catch it.
def main
# The rescued exception is available in the rescue block.
begin
may_raise
rescue ex
puts "Recovered. Error:\n #{ex.message}"
end
# This code will not run, because may_raise raises an exception.
# The execution of main stops at the point of the exception and
# resumes in the rescue block.
puts "After may_raise()"
end
main
To run the program:
$ crystal run recover.cr
Recovered. Error:
a problem
In Crystal, exceptions are used for error handling, which is similar to panics in some other languages. The begin
/rescue
construct allows you to catch and handle these exceptions, providing a way to recover from errors and continue execution.
The rescue
block catches any exception raised in the begin
block. If an exception is caught, the code in the rescue
block is executed, allowing you to handle the error gracefully. This is particularly useful in scenarios where you want to prevent a single error from crashing your entire application.