-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexceptions.rb
More file actions
108 lines (86 loc) · 1.49 KB
/
exceptions.rb
File metadata and controls
108 lines (86 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
require_relative 'helpers'
header('Exceptions')
begin
3 / 0
rescue
puts 'Ups!'
end
separator
def my_method
3/0
true
rescue
puts 'Error in my method!'
false
end
puts my_method
separator
begin
3/0
rescue StandardError
puts 'StandardError'
rescue
puts 'Some other error'
end
separator
# I can raise an error
def my_second_method
raise 'What an error!'
end
begin
my_second_method
rescue RuntimeError
puts 'raise by default throws a RuntimeError'
end
separator
# I can specify the error type when I raise an error
def my_third_method
raise ArgumentError, 'What an argument error!'
end
begin
my_third_method
rescue ArgumentError
puts 'Error type can be specified'
end
separator
begin
my_third_method
rescue
# $! refers to the last exception raised, it's the same as using Exception => e; e.message
puts $!.message
end
separator
# rescue/else/ensure
def rescue_else_ensure
3/1
rescue
puts 'Something went wrong'
else
puts 'great! not errors.'
ensure
puts 'Cleaning up everything!'
end
puts rescue_else_ensure
# great! not errors.
# Cleaning up everything!
separator
# retry is useful for example if you are calling an API that usually fails
def rescue_retry
3/0
rescue Exception => e
attempts ||= 0
attempts += 1
if attempts < 3
puts e.message + '. Retrying'
# retry returns the execution to the beginning of the method
retry
else
puts 'No way! It failed'
raise
end
end
begin
puts rescue_retry
rescue
puts 'retry failed'
end