Begin # Start
Raise .. # Throw an exception
Rescue [exceptiontype = standardexception] # Capture exceptions of the specified type. The default value is standardexception.
$! # Exception Information
$ @ # Indicates that an exception occurs.CodeLocation
Else # Other exceptions
..
Ensure # Enter the code block whether there are any exceptions.
End # End
This is an exception handling structure, which can be combined with $! Cause of the error, and make a small error capture and prompt at $ @ error locationProgramFor example
Begin
Puts
Puts " File: # {name = argv. Shift} "
File = Open (name)
I = 0
File. Read. each_line { | Line | Puts " # {I + = 1}. # {Line} " }
Puts
Rescue
Puts " Error: # {$ !} At :#{$ @} "
Ensure
File. Close
End
The preceding applet reads a specified file and adds the row number to output the file. When an error is generated, an error message and a prompt are displayed. You can intentionally enter a non-existent file name.
Actually, begin is equivalent to a try of C #.
Rescue is equivalent to catch of C #
Ensure is equivalent to finaly of C #.
Raise is equivalent to the throw of C #.
Structure of exception classes
Exception
Object
- Exception
-
- (Interrupt) (Ruby 1.7 featuresLocation before version 1.6)
-
- Nomemoryerror
-
- Scripterror
- Loaderror
- (Nameerror) (Ruby 1.7 featuresLocation before version 1.6)
- Notimplementederror
- Syntaxerror
-
- Signalexception
- Interrupt (Ruby 1.7 features)
- Standarderror
- Argumenterror
- Indexerror
- Keyerror (Ruby 1.9 features)
- Ioerror
- Localjumperror
- Nameerror (Ruby 1.7 features)
- Nomethoderror (Ruby 1.7 features)
- Rangeerror
- Regexperror
- Runtimeerror
- Securityerror
- Systemcallerror
- Systemstackerror
- Threaderror
- Typeerror
- Zerodivisionerror
-
- Systemexit
-
- Fatal