Ruby Exception Handling: Rescue

Source: Internet
Author: User

A running Program An unexpected problem occurs. A file to be read does not exist. When you want to store some data, the disk is full. You may enter inappropriate data.

Ruby> file = open ("some_file ")
Err: (eval): 1: In 'open': no such file or directory-some_file

A robust program will handle these problems reasonably and beautifully. dealing with exceptions is an annoying task. c programmers are required to check the return values of every system call that may cause errors and make immediate decisions.

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 here ...*/
}
...

This boring job will make programmers become sloppy and ignore it. As a result, the program cannot cope with exceptions. On the one hand, this will also reduce the readability of the program, because too many error processing makes sense.CodeIt also becomes messy.

In Ruby, like other modern languages, we can handle exceptions in code domains through isolation. Therefore, this has an amazing effect, but it will not cause excessive burden on programmers or others who want to read it later. the code field starts from begin until an exception occurs, which leads to a code field for error handling marked by rescue. if the exception does not occur, the rescue code will not be used. the following code returns the first line of the text file. If an exception exists, Nil is returned.

Def first_line (filename)
Begin
File = open ("some_file ")
Info = file. Gets
File. Close
Info # Last thing evaluated is the return value
Rescue
Nil # Can't read the file? Then don't return a string
End
End

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

Begin
File = open ("some_file ")
Rescue
File = stdin
End
Begin
#... Process the input...
Rescue
#... And deal with any other exceptions here.
End

Retry is used for rescue code to re-execute 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 this is still a bit flawed. A non-existing file will cause retry without stopping. You should note this when using retry for exception handling.

Each ruby library submits an exception when an error occurs. You can explicitly submit the exception in your code. use raise to submit an exception. it carries a parameter, that is, a string that describes the exception. the parameter is optional but should not be omitted. then it can use 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.