Ruby is a dynamic scripting language that everyone knows.
The problem I want to discuss today is the exception handling mechanism in ruby.Code:
1 Class socketerror < Standarderror
2 End
3
4 Class Test
5 @ Host = " 192.168.0.1 "
6 @ Port = 8000
7 Def opensocket
8 Ret_str = " Socket open fail "
9 Begin
10 Socket = Tcpsocket . Open ( @ Host , @ Port )
11 Ret_str = " Socket open successed! "
12 Rescue => E
13 Puts " Socket Error "
14 Raise socketerror
15 End
16 Return Ret_str
17 End
18 End
19
20 # ############################
21 T = Test . New
22 Begin
23 Str = T . Opensocket ()
24 Puts Str
25 Rescue socketerror
26 Puts " Socket open fail in opensocket Method "
27 End
28 # ############################
The printed results of this code should be known as follows:
Socket Error
Socket open fail in opensocket Method
See the following code.
1 Class socketerror < Standarderror
2 End
3
4 Class Test
5 @ Host = " 192.168.0.1 "
6 @ Port = 8000
7 Def opensocket
8 Ret_str = " Socket open fail "
9 Begin
10 Socket = Tcpsocket . Open ( @ Host , @ Port )
11 Ret_str = " Socket open successed! "
12 Rescue => E
13 Puts " Socket Error "
14 Raise socketerror
15 Ensure
16 Return Ret_str
17 End
18 End
19 End
20
21 # ############################
22 T = Test . New
23 Begin
24 Str = T . Opensocket ()
25 Puts Str
26 Rescue socketerror
27 Puts " Socket open fail in opensocket Method "
28 End
29 # ############################
30
31
What are the returned results of this code?
Is it consistent with the result returned by the above Code?
The result is:
Socket Error
Socket open fail
You may wonder, "Why can't I receive exceptions in the resure of the outer layer because the returned result is socket open fail? Why can't I print socket open fail in opensocket method"
This is the question to be discussed today.
The difference between the second code and the first code is that the position of the Return Statement is different. In the second code, place return in Ensure. The first code is placed after the begin... end language.
This is actually the reason for the above results. In code segment 2, we just want to return the value we want in the aftermath of an exception.
This will lead to a result that the raise exception in the previous rescue will be "eaten" because of this return. That is to say, at this time, he will not throw the raise exception and handle it himself,
In fact, return in ensure is not allowed in strongly typed languages.
For example, in the C # language, return is not allowed in try... catch... Finally, which avoids such a problem.