Ruby Exception Handling

Source: Internet
Author: User
Exception Handling is a common problem in the development process. Basically, all advanced languages have their own exception handling systems. Ruby is no exception and is easy to use.

The raise method is used to throw exceptions in Ruby. Remember, this is a method provided by ruby kernel, not a keyword. At the same time, Ruby also provides an alias fail for this method, you can use fail instead of raise to throw an exception as follows:

Raise # Throw a default runtimeerror
Raise "some error message" # Throw A runtimeerror whose message is "some error message"
Raise argumenterror # Throw a message-free argumenterror
Raise argumenterror, "Bad Data" # throw an argumenterror whose message is "Bad Data"
Raise argumenterror. New ("Bad Data") # Same as above
Raise argumenterror, "Bad Data", caller [0] # throws an exception that contains the Message format filename: line or filename: Line: In 'method '.

In the above Code, raise can be replaced by the alias fail. When the exception type is not explicitly specified, Ruby throws a runtimeerror by default. The information thrown in the last example contains the file where the current error is located, information about the method where the number of rows already exists. The information is stored in the caller array, which contains information about the method caller. The first element contains information about the method caller, the second information contains the Caller information of the method caller, and so on. This array is useful when we want to know where the exception is and where the call is thrown.

Def func1
Puts caller # print Caller information
End

Def func2
Func1 # Row 6
End

Def func3
Func2 # Row 10
End

Func3 # final caller, row 13

# Running result
# Test. RB: 6: In 'func2'
# Test. RB: 10: In 'func3'
# Test. RB: 13

From the code above, caller records the file name, number of lines, and method of each caller.

The preceding section describes how to throw a ruby exception and the functions of the caller array. Next, let's take a look at how to capture exceptions in Ruby. in Java, the exception is captured in try... catch, while Ruby is in begin... capture exceptions in the end code block. Use the rescue keyword in this code block to capture exception types. Note that this is a keyword rather than a method.

Begin
... # The code may be abnormal.
Rescue errortype1 # type of exception to be captured
...... # Code for Exception Handling
Rescue errortype2 # types of exceptions to be captured
...... # Code for Exception Handling
End

The above code is an approximate example of capturing exceptions. In the begin and end code blocks, the rescue is used to capture the exception types and then perform appropriate processing, however, if the thrown exception type is not displayed, how can this problem be solved? That is, use else at the end, as follows:

Begin
... # The code may be abnormal.
Rescue errortype1 # type of exception to be captured
...... # Code for Exception Handling
Rescue errortype2 # types of exceptions to be captured
...... # Code for Exception Handling
Else
...... # If none of the above Code types are captured, run the code section.
End

Now there is another question. What should I do if I want to obtain the exception information? See the following code:

Begin
Raise argumenterror, "Bad Data"
Rescue => err
Puts err
End

By rescue => variable, you can save the exception as a variable. Another problem has been solved. What is the problem? Ah, by the way, in the use of Java, for example, after the connection is used for database connection, the resources must be cleaned up in finally blocks, but how can we clean up these resources in Ruby? Take a look at the following code:

Begin
Raise argumenterror, "Bad Data"
Rescue => err
Puts err
Ensure
... # Execute cleanup
End

From the code above, we can see that Ruby provides the keyword ensure, which serves the same purpose as finally in Java. Regardless of any exception, the code under this keyword must be executed before exiting the code block. At the same time, Ruby also provides the restoration function. If we need to restore the code block after throwing an exception and handling the exception, we will re-execute the code block using retry.

As mentioned above, exception capturing and processing must be performed in the begin-end code block. Do you need to write the begin-end keywords at any time? In Ruby, the method is actually an implicit begin-end code block. Therefore, you can omit begin to capture and handle exceptions in the method.

This article is based on the Ruby way book. If you have any questions, please correct me. Thank you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.