Ruby Exception Handling

Source: Internet
Author: User

I. Common ruby exception information:

Exception name

Common Causes

How to throw

RuntimeError

Default exception thrown by raise

Raise

NoMethodError

The corresponding method cannot be found for the object.

A = Oject. new
A. jackmethod

NameError

The interpreter encounters an identifier that cannot be parsed as a variable or method name.

A = jack

IOError

Read closed streams, write read-only streams, or similar operations

STDIN. puts ("cannot write ")

Errno: error

File IO-related errors

File. open (-10)

TypeError

The method accepts parameters that cannot be processed.

A = 3 + "abc"

ArgumentError

An error occurred while passing the number of parameters.

Def o (x) endO (1, 2, 3)

 

Ii. Format

Refer to java exception handling.

try{  -------------- begin}catch(){  ---------rescue }finally{  ---------ensure}   ----------------end

Possible exception information may be contained between begin and end.

Specify the exception following rescue. The default value can be used by default. Rescue is paired with else. else does not specify an exception or has no exception.

Ensure is equivalent to finally in java and is not explained much.

Two important variables: $! : Exception description, $ @: Location of the exception.

Let's look at an example:

If _ FILE _ = $0 a = 10 B = 20 c = 0 begin ad = a/B ac = a/c rescue puts "exception # {$ !}, Location: # {$ @} "else puts" no exception "ensure puts" enters class finally zone "endend

Execution result:
Exception divided by 0, Location: exception. rb: 15: in '/' exception. rb: 15
Enter the class finally Area

3. Saving exception information to variables

Use: rescue => e

Print: puts e. to_s
Use the preceding example to replace rescue with the following:

Rescue => e puts "has an exception # {$ !}, Location: # {$ @} "puts e. to_s + "....."

Execution result:

Exception divided by 0, Location: exception. rb: 15: in '/' exception. rb: 15
Divided by 0 .....
Enter the class finally Area

 

 

 

 

 

 

 

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.