An unexpected problem occurs in a running program. 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. too much error processing makes meaningful code 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