I. Common anomalies
Exception name |
Common causes |
How to Throw |
RuntimeError |
Default exception thrown by raise |
Raise |
Nomethoderror |
Object cannot find a corresponding method |
A=oject.new A.jackmethod |
Nameerror |
The interpreter encounters an identifier that cannot be resolved to a variable or method name |
A=jack |
IOError |
Reads a closed stream, writes a read-only stream, or a similar operation |
Stdin.puts ("Cannot write") |
Errno::error |
A class of errors related to file IO |
File.Open (-10) |
TypeError |
Method accepts a parameter that it cannot handle |
a=3+ "ABC" |
Argumenterror |
Error passing the number of parameters |
def o (x) End O (All-you-do) |
Second, catch the exceptioncatching exceptions with rescue#用rescue捕获异常beginResult=20/0puts resultRescueZerodivisionerrorputs "Zero Error"RescuePuts "Unknow error"EndOutput: Zero Error three,raise throws an exceptiondef divide (x) Raise Argumenterror if X==0end begindivide (0) Rescue argumenterrorputs "Argumenterror" End output: Argumenterror Iv. Save the exception to the variable def divide (x) Raise Argumenterror if X==0end begindivide (0)Rescue =>ePuts E.to_send output: Argumenterror v. Create exception classthrowexceptionl<exceptionPuts "error L" End Beginraise throwexceptionl, "Got error" rescue throwexceptionl=>eputs "error #{e}" End output: Error lerror Got error
Sample Ruby exception handling structure code:
- Begin #开始
- Raise. #抛出异常
- Rescue [Exceptiontype =
Standardexception]
#捕获指定类型的异常 Default value is Standardexception
- $! #表示异常信息
- [Email protected] #表示异常出现的代码位置
- else #其余异常
- ..
- Ensure #不管有没有异常, enter the code block
- End #结束
Can be combined with $! error causes, and [email protected] Error location to do a bug capture and prompt the small program, such as:
- Begin
- Puts
- Puts "file: #{name = argv.shift}"
- File = open (name)
- i = 0
- File.read.each_line
{|line| puts "#{i+=1}.#{line}"}
- Rescue
- Puts "error:#{$!} At:#{[email protected]} "
- Ensure
- File.close
- End
Ruby Error Handling and exceptions