Ruby Exceptions
Exceptions and execution are always linked together. If you open a file that does not exist and do not handle the situation properly, your program is considered to be of low quality.
If an exception occurs, the program stops. Exceptions are used to handle various types of errors that may occur during program execution, so that appropriate action can be taken instead of letting the program stop completely.
Ruby provides a perfect mechanism for handling exceptions. We can put code that may raise an exception in a begin/end block, and use a rescue clause to tell Ruby exactly which type of exception to handle.
Syntax
begin
at the beginning
raise
..
Throwing an Exception
rescue
[
ExceptionType
=
StandardException
]
The default value for catching a specified type of exception is StandardException
$!
Represents the exception message
$@
Represents the code location where the exception occurred
else
All other exceptions
..
ensure
Whether or not an exception occurs, enter this code block
end
at the end
From the begin to rescue Everything in it is protected. If an exception occurs during execution of the block, control is passed to the rescue and end block between them.
For begin Each rescue clause in the block, Ruby compares the raised exception with each parameter in turn. If the exception named in the rescue clause is the same type as the currently raised exception, or is its parent class, the match succeeds.
If the exception does not match all the specified error types, we can use a rescue after all the else clause.
Example
!/usr/bin/ruby
begin
file
=
open
(
"
/unexistant_file
"
)
if
file
puts
"
File opened successfully
"
end
rescue
file
=
STDIN
end
file
,
"
==
"
,
STDIN
,
"
\n
"
The output of running the above example is. You can see thatSTDIN replaced file , becauseOpenfailed.
#==#
Use retry Statement
You can use the rescue block catches the exception and then uses the retry statement to start execution from the beginning begin block.
Syntax
begin
The exception raised by this code will be caught by the following rescue clause
rescue
This block will catch all types of exceptions
retry
This will move control to the beginning of begin
end
Example
!/usr/bin/ruby
begin
file
=
open
(
"
/unexistant_file
"
)
if
file
puts
"
File opened successfully
"
end
rescue
fname
=
"
existant_file
"
retry
end
The following is the processing flow:
- An exception occurs when opening.
- Jump to rescue. fname is reassigned.
- Jump to the beginning of begin via retry.
- This time the file is opened successfully.
- Continue with the basic process.
**Note:** If the renamed file does not exist, this example code will try indefinitely. Therefore, when handling exceptions, use the retry。
Use raise Statement
You can use the raise statement to raise exceptions with caution. The following method raises an exception when called. Its second message will be output.
Syntax
raise
or
raise
"
Error Message
"
or
raise
ExceptionType
,
"
Error Message
"
or
raise
ExceptionType
,
"
Error Message
"
condition
The first form simply re-raises the current exception (or raises a RuntimeError if there is no current exception). This is used in exception handlers that need to explain the exception before passing it on.
The second form creates a new RuntimeError exception, setting its message to the given string. The exception is then raised to the call stack.
The third form creates an exception using the first argument, and then sets the associated message to the second argument.
The fourth form is similar to the third; you can add any additional conditional statements (such as unless) to raise the exception.
Example
!/usr/bin/ruby
begin
puts
'
I am before the raise.
'
raise
'
An error has occurred.
'
puts
'
I am after the raise.
'
rescue
puts
'
I am rescued.
'
end
puts
'
I am after the begin block.
'
The above example produces the following output:
I am before the raise.
I am rescued.
I am after the begin block.
Another example demonstrating the raise usage:
Example
!/usr/bin/ruby
begin
raise
'
A test exception.
'
rescue
Exception
=>
e
puts
e
.
message
puts
e
.
backtrace
.
inspect
end
The above example produces the following output:
A test exception.
["main.rb:4"]
Use ensure Statement
Sometimes, whether or not an exception is raised, you need to ensure that some processing is completed when the code block ends. For example, you may have opened a file on entry, and when you exit the block, you need to make sure the file is closed.
ensure The clause does exactly this. ensure is placed after the last rescue clause and contains a code block that is always executed when the block terminates. It doesn't matter whether the block exits normally, whether an exception is raised and handled, or whether it terminates due to an uncaught exception,ensure the block will always run.
Syntax
begin
.. Process
.. Raising an exception
rescue
.. Handling the error
ensure
.. Finally ensuring execution
.. This will always execute
end
Example
begin
raise
'
A test exception.
'
rescue
Exception
=>
e
puts
e
.
message
puts
e
.
backtrace
.
inspect
ensure
puts
"
Ensuring execution
"
end
The above example produces the following output:
A test exception.
["main.rb:4"]
Ensuring execution
Use else Statement
If a else clause is provided, it is generally placed after the rescue clause, and the body of any ensure before.
else clause is executed only if no exception was raised in the main body of the code.
Syntax
begin
.. Process
.. Raising an exception
rescue
.. Handling the error
else
.. Executes if there is no exception
ensure
.. Finally ensuring execution
.. This will always execute
end
Example
begin
Raise 'A test exception.'
puts
"
I'm not raising exception
"
rescue
Exception
=>
e
puts
e
.
message
puts
e
.
backtrace
.
inspect
else
puts
"
Congratulations-- no errors!
"
ensure
puts
"
Ensuring execution
"
end
The above example produces the following output:
I'm not raising exception
Congratulations-- no errors!
Ensuring execution
Use the $! variable to capture the raised error message.
Catch and Throw
The raise and rescue exception mechanism can abandon execution when an error occurs; sometimes you need to break out of deeply nested structures during normal processing. This is where catch and throw come in handy.
catch defines a block that uses a given name (which can be a Symbol or String) as a label. The block executes normally until it encounters a throw.
Syntax
throw
:
lablename
.. This will not be executed
catch
:
lablename
do
.. The matching catch to be executed after encountering a throw
end
or
throw
:
lablename
condition
.. This will not be executed
catch
:
lablename
do
.. The matching catch to be executed after encountering a throw
end
Example
In the following example, if the user types '!' in response to any prompt, a throw is used to terminate the interaction with the user.
Example
def
promptAndGet
(
prompt
)
prompt
res
=
readline
.
chomp
throw
:
quitRequested
if
res
==
"
!
"
return
res
end
catch
:
quitRequested
do
name
=
promptAndGet
(
"
Name:
"
)
age
=
promptAndGet
(
"
Age:
"
)
sex
=
promptAndGet
(
"
Sex:
"
)
..
Handling the Message
end
promptAndGet
(
"
Name:
"
)
The above program requires human interaction, which you can try on your computer. The output of running the above example is:
Name: Ruby on Rails
Age: 3
Sex: !
Name:Just Ruby
The Exception Class
Ruby's standard classes and modules raise exceptions. All exception classes form a hierarchy, including the Exception class at the top. The next level consists of seven different types:
- Interrupt
- NoMemoryError
- SignalException
- ScriptError
- StandardError
- SystemExit
Fatal is another exception in this layer, but the Ruby interpreter only uses it internally.
Both ScriptError and StandardError have subclasses, but we don't need to know those details here. The most important thing is to create our own exception classes, which must be subclasses of the Exception class or its descendants.
Let's look at an example:
Example
class
FileSaveError
<
StandardError
attr_reader:
reason
def
initialize
(
reason
)
@reason
=
reason
end
end
Now, look at the following example, which will use the above exception:
Example
File
.
open
(
path
,
"
w
"
)
do
|
file
|
begin
Writing data ...
rescue
An error occurred
raise
FileSaveError
.
new
(
$!
)
end
end
Here, the most important line is raise FileSaveError.new($!). We call raise to signal that an exception has occurred, passing it a new instance of FileSaveError, due to the specific exception that caused the data write to fail.