Our first example demonstrates error handling in Crystal. Crystal uses exceptions for error handling, which is different from the explicit return value approach used in some other languages.
To run the program, save it as errors.cr and use the Crystal compiler:
In Crystal, we use exceptions for error handling. Instead of returning error values, we raise exceptions when an error occurs. We can define custom exception classes for specific error scenarios.
The begin/rescue blocks in Crystal are similar to try/catch blocks in other languages. They allow us to handle different types of exceptions separately.
Crystal doesn’t have a direct equivalent to Go’s error wrapping and errors.Is functionality. Instead, you can create custom exception hierarchies if you need to check for specific error types.
This example demonstrates basic error handling in Crystal, including raising and catching custom exceptions, which is the idiomatic way to handle errors in this language.