Ruby Exception Handling: Rescue_ruby topics

Source: Internet
Author: User
Tags error handling exception handling stdin
A running program often encounters unexpected problems. A file to read does not exist; When you want to save some data, the disk is full; The user may enter inappropriate data.

ruby> file = open ("Some_file")
ERR: (eval): 1:in ' open ': No such file or Directory-some_file


A robust program handles these problems reasonably and beautifully. Facing those anomalies is a tiresome job. C Programmers are required to check the return value of each system call that could cause an error and make a decision immediately.

FILE *file = fopen ("Some_file", "R");
if (file = = NULL) {
fprintf (stderr, "File doesn ' t exist.\n");
Exit (1);
}
Bytes_read = Fread (buf, 1, bytes_desired, file);
if (Bytes_read!= bytes_desired) {
* Do more error handling ... *
}
...


This boring job will make the programmer end up sloppy and ignore it, and the result is that the program can't handle the exception. On the one hand, this also reduces the readability of the program. Because too much error handling makes meaningful code messy.

In Ruby, as in other modern languages, we can deal with exceptions in the code domain by isolating them, so this has an amazing effect without unduly burdening the programmer or others who want to read it. The Code field begins with begin until an exception is encountered. This will result in a shift to an error-handling code field marked by rescue. If the exception does not occur, the rescue code will not be used. The following code returns the first line of a text file and returns nil if there is an exception.

def first_line (filename)
Begin
File = Open ("Some_file")
info = file.gets
File.close
Info # Last thing evaluated are the return value
Rescue
Nil # Can ' t read the file? Then don ' t return a string
End
End


Sometimes we want to do creative work around problems. Here, if the file does not exist, we use the standard input instead:

Begin
File = Open ("Some_file")
Rescue
File = STDIN
End
Begin
# ... process the input ...
Rescue
# ... and deal with any other exceptions.
End


Retry is used to rescue code representations and to rerun the begin code. This allows us to compress the previous example:

fname = "Some_file"
Begin
File = open (fname)
# ... process the input ...
Rescue
fname = "STDIN"
Retry
End


But there are still a few flaws. A nonexistent file will cause retry to be stopped. You should be aware of this when you use retry for exception handling.

Each Ruby library submits an exception when it encounters an error. You can explicitly submit exceptions in your own code. Use raise to submit an exception. It takes a parameter, which is a string that describes the exception. parameters are optional but should not be omitted. It can then be passed through a special global variable $! Access.

Ruby> raise "Test Error"
Test error
Ruby> begin
| Raise "Test2"
| Rescue
| Print "An error occurred:", $!, "\ n"
| End
An error OCCURRED:TEST2
Nil

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.