Ruby Exception Handling: Rescue

Source: Internet
Author: User
Tags error handling exception handling

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, which 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 is the return value
rescue
Nil # Can ' t read the file? Then don ' t return a string
end

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.