For example, suppose you want to parse certain data and store only specific data in the database. Among them, if there is an extension that cannot be parsed, an error will occur, processing will be interrupted, and a bug will occur.
Therefore, exception handling is convenient, and it is possible to perform processing in the case of an exception case without interrupting the processing.
Indeed, it is possible to realize if given, give back, give back
.
This time, let's take a simple calculation as an example and look at exception handling.
In Ruby, when I try to divide 10 by 0, I get an error.
python
puts 10 / 0
puts "Hello"
divided by 0 (ZeroDivisionError)
The process is interrupted in the middle.
Therefore,
--Enclose the part that is likely to be the target of the error with begin
.
--Describe the processing when an error occurs in rescue
.
python
begin
10 / 0
rescue
p "Does not break at 0"
end
puts "Hello"
"Does not break at 0"
"Hello"
The processing was not interrupted, and both the error processing and the normal processing were executed.
Rescue without begin
python
puts 10 / 0 rescue 0
puts 10 / nil rescue 0
0
0
python
begin
10 / 0
rescue => e
puts e
end
puts "Hello"
divided by 0
Hello
The error object can be stored in the variable e and output.
python
begin
10 / 0
rescue NoMethodError
puts "There is no such method"
rescue ZeroDivisionError
puts "Does not break at 0"
end
Does not break at 0
Since it corresponds to the second error message, it responds to the rescue.
If the parent of the target exception class is described first, that is processed first.
python
begin
10 / 0
rescue StandardError
puts "Basic error"
rescue ZeroDivisionError
puts "Does not break at 0"
end
Basic error
The intended use is
python
begin
raise NoMethodError
rescue => e
p e
end
NoMethodError
Let's inherit the exception class (StandardError class).
python
class Hoge < StandardError
end
begin
raise Hoge
rescue => e
p e
end
#<Hoge: Hoge>
python
num = 0
begin
puts 10 / num
rescue ZeroDivisionError => e
puts e
num = 1
retry
end
puts "Finished"
divided by 0
10
Finished
In the first loop, there was an error In the second loop, processing is performed normally.
python
begin
puts "No exception"
rescue => e
puts e
ensure
puts "Hello"
end
No exception
Hello
ensure is always performed at any time.
python
begin
10 / 0
rescue => e
puts e.class
puts e.class.superclass
puts e.class.superclass.superclass
puts e.class.superclass.superclass.superclass
end
ZeroDivisionError
StandardError
Exception
Object
Exception is the base class and Object is its parent
Recommended Posts