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