How to indicate that something has gone wrong?
An exception object is raised (or thrown).
Exception can occur during execution of code. By default, ruby excution ends when an exception occurs. But, you can declare exception handlers.
The program below raises an exception whenever the method raise_exception is called.
This wil show:
This raises an exception using the RuntimeError class.
Exceptions can be handled with the rescue keyword.
In the example below we raise an exception and handle it:
Lets create a situation in which Ruby raises an exception, we’ll divide by zero:.
x = 1 / 0
rescue ZeroDivisionError => e
puts 'Handling exception'
Instead of crashing, Ruby handles the exception and continues execution.
You can use other classes to generate errors, like a custom class:
class CustomError < StandardError