Best 5 practices of exception handling【Ruby】
Recently, I studied exception handling of Ruby. There is a book which summarize them. They are so informative, so write them down in this article.
1. Don’t use rescue easily
When exception happens, processing is continued by using rescue. But, exception means program can’t be executed rightly. If it is not operated rightly, we should stop that process. Otherwise, perhaps critical problem happens. When serious error happens, we must look for the cause and fix them.
2. Rescue with information
Of course, to rescue is sometimes right. If you do that, you must leave the information of errors. How to leave them is below.
begin # errors maybe happens
rescue => e
puts "#{e.class}: #{e.message}"
puts e.backtrace
end
In order to find the cause, we should have information as much as possible. By writing code above, you can get class of exception, message of it and backtrace.
3. The range of exception handling must be narrow as much as possible
When you code exception handling, the target must be narrow. If you the range is too broad, It becomes difficult to catch the problems.
begin
year = params[:year]
month = params[:month]
day = params[:day]
Date.new(year, month, day)
rescue
nil
end
In this case, I want to get nil if the date is invalid(ex. 99 month 99 day). But in this code, you get nil when the params is invalid. When only Date.new is invalid, want nil. So, the right code is below.
year = params[:year]
month = params[:month]
day = params[:day]
begin
Date.new(year, month, day)
rescue
nil
end
You can get nil when only date.new is invalid.
4. Use conditional branch rather than exception handling
year = params[:year]
month = params[:month]
day = params[:day]
if Date.valid_date?(year, month, day)
Date.new(year, month, day)
end
nil
end
Even if you don’t use exception handling, can determine Date is valid or not. Using conditional branch results in more readable code and you can have high performance of the system.
5. When the unexpectable condition happens, the process must be ended.
def upcase(str)
case str
when :a
"A"
when :b
"B"
when :c
"C"
else
"D"
end
end
In this case, whatever string is gotten except for a, b and c, the return is D. This process is not right.
def upcase(str)
case str
when :a
"A"
when :b
"B"
when :c
"C"
else
raise ArgumentError, "it is invalid string #{str}"
end
end
This process is right. When the system get string except for a, b and c, it raises ArgumentError. User can know his/her parameter is not valid.
comment
You don’t always need to use exception handling and must ascertain when to use it.