[RoR series of the 2014 learning plan] Step 2-familiarize yourself with the Ruby language (3/n)

Source: Internet
Author: User

Exception Handling in Ruby

Ruby predefines common exception types, as shown in:


All Exception classes are derived from the base class Exception, which is similar to Java, C #, and Python.

Ruby special point-when an exception occurs, ruby will put the exception object associated with this exception into the global variable $! . (This section is a bit unclear, understanding... Attach the original text)

When an exception is raised, and independent of any subsequent exception handling, Ruby places a reference to the associated Exception object into the global variable $! (The exclamation point presumably refreshing ing our surprise that any of our code cocould cause errors ).

Exception Handling example:

Begin
Eval string
Rescue SyntaxError, NameError => boom
Print "String doesn' t compile:" + boom
Rescue StandardError => bang
Print "Error running script:" + bang
End

Ruby uses the rescue keyword filtering exception, which is different from catch, which is common in other languages. You can have multiple rescue in the begin block, and each rescue can have multiple exception types.

If there is no type parameter behind rescue, Ruby uses StandardError as the default value.

System Error

In POSIX systems, errno is a de facto standard. The system or application uses errno to report errors. Ruby wraps these errors into exceptions. These exception classes are derived from SystemCallError. We can see them from the class names, such as Errno: EIO, Errno: EGAAIN, and so on.

The Errno fields of these classes can correspond to the errno values of the system one by one.

Errno: EAGAIN: Errno 35
Errno: EPERM: Errno 1
Errno: EIO: Errno 5
Errno: EWOULDBLOCK: Errno 35
   

 

With try/catch, Is there finally?

This can be. Ensure is what we want. It's straightforward. Don't say it.

F = File. open ("testfile ")
Begin
# .. Process
Rescue
#. Handle error
Ensure
F. close unless f. nil?
End

Let's look at something special-else

F = File. open ("testfile ")
Begin
# .. Process
Rescue
#. Handle error
Else
Puts "Congratulations no errors! "
Ensure
F. close unless f. nil?
End

The else clause after rescue will be executed when no exception is thrown. -It seems that this is useless.

Below are some useful tricks.

@ Esmtp = true
Begin
# First try an extended login. If it fails because
# Server doesn' t support it, fall back to a normal login
If @ esmtp then
@ Command. ehlo (helodom)
Else
@ Command. helo (helodom)
End
Rescue ProtocolError
If @ esmtp then
@ Esmtp = false
Retry
Else
Raise
End
End

The red and bold retry is interesting. In the above Code, set esmtp to true and try to log on. If it fails, set it to false and try again. Well, I think it is quite useful.

How to capture exceptions is finished. The next step is the next step.Throw an exceptionNow

Raise
Raise "bad mp3 encoding"
Raise InterfaceException, "Keyboard failure", caller

The raise method here is actually the Kernel. raise method.

The first raise does not contain any parameters. It is used to throw the current exception to the outer layer. If no exception exists, a RuntimeError is thrown.

The second raise carries a string parameter, which is used to construct a RuntimeError exception and then throws it.

The third raise has three parameters, the first is the exception type, the second is the exception message, and the third is the call stack. Kernel. caller is used to generate a call stack.

The catch/throw in Ruby is used in this way.

When an error occurs, how does one jump out of the layer-by-layer logic? C-style longjump? No. Ruby provides convenient catch/throw usage.

Catch(: Done) do
While line = gets
Throw: Done unless fields = line. split (/\ t /)
Songlist. add (Song. new (* fields ))
End
Songlist. play
End

Catch defines a code block named done. The code block runs normally until it encounters an exception or ends normally.

Another example:

Def prompt_and_get (prompt)
Print prompt
Res = readline. chomp
Throw: quit_requested if res = "! "
Res
End

Catch: quit_requested do
Name = prompt_and_get ("Name :")
Age = prompt_and_get ("Age :")
Sex = prompt_and_get ("Sex :")
#..
# Process information
End

The ruby notes before Spring Festival are here. I hope you will have money right away. You will have a room right away and an object right away.




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.