RUBY TIMES FOR THE ERROR HANDLING STRUCTURE
Posted on 2011-03-09 16:31 blackwind 阅读(202) 评论(0) 收藏 举报It is very happy to come back . This time , we will learn about RUBY ERROR HANDLING STRUCTURE.If you were a C/C++ programmer,it is very simple. ERROR HANDLING STRUCTURE is the same between C/C++ and RUBY.It is sure that the key word is different.OK, let's start our RUBY time.
BEGIN
..........
..........
RESCUE
RAISE
RETRY
ELSE
ENSURE
END
We should face that no matter how carefully we wrote our programs ,some unforeseen errors will still be encourtered .But don't worry
about that.Every programming language exists ERROR handling struture. As ruby ,the main frame of error handling is above.
If you want to catch the exception generated in your new code , first of all, to tell effect area is very important.Ruby traps exceptions when it find the keyword "begin",and will finish this job with "end ".There are many types of exception.Different exceptions deals with different methods.So how to tell ruby that ? We can use "rescue" to let exception match dealing method.Most of time.there will not be only one exception existing.As a result , what exception we predict ,what method is on call.
The more exception happen in program , the more rescue should be match in exception handling.when you want to read the H disk,but your pc does not exist H disk.At this time , runtime gives out an ErrNO "ENOENT".On my pc , D: is my DVD driver. There is no disk in it ,when my program tries to log on to DVD driver,Ruby returns this type of ERROR "EACCES".There are a variety of Errno, you rescue them in different case.In fact,you can rescue all type of Errnos in your program.Some of them will be effect ,so it must to find out which is need.or else you will waste your times to write uneffect code.
RAISE is easy to understand . Do you still remember "catch" in C++? yes, they are the same.Exceptions will be thrown by runtime when logic is out of control.At this time , Ruby checks every rescue to compare with them .Matching successfully,Ruby excutes RAISE method and runtime stop to wait method finish.
The main effect of RETRY is to let rumtime back to the first of the program . Ruby points to the start and excutes again.Why it needs to redo .I don't know.
Sometimes , an error happens , runtime catches it , then check out whether there is method to deal with it in the RESCUE.There is a lot of errers during the proceduce runing of program . It does not exist a structure to handling all of the error. Consequently,ELSE is nessary when an unknow error generated. It could be a method or a tips of the error.
ENSURE which is like its name's meaning can confirm the following code will be excute. You can print error message in RESCUE.All error handling logic set in ENSURE.
浙公网安备 33010602011771号