text
stringlengths 0
444
|
|---|
# handle IOError
|
end
|
# good
|
def with_io_error_handling
|
yield
|
rescue IOError
|
# handle IOError
|
end
|
with_io_error_handling { something_that_might_fail }
|
with_io_error_handling { something_else_that_might_fail }
|
----
|
=== Suppressing Exceptions [[dont-hide-exceptions]]
|
Don't suppress exceptions.
|
[source,ruby]
|
----
|
# bad
|
begin
|
do_something # an exception occurs here
|
rescue SomeError
|
end
|
# good
|
begin
|
do_something # an exception occurs here
|
rescue SomeError
|
handle_exception
|
end
|
# good
|
begin
|
do_something # an exception occurs here
|
rescue SomeError
|
# Notes on why exception handling is not performed
|
end
|
# good
|
do_something rescue nil
|
----
|
=== Using `rescue` as a Modifier [[no-rescue-modifiers]]
|
Avoid using `rescue` in its modifier form.
|
[source,ruby]
|
----
|
# bad - this catches exceptions of StandardError class and its descendant classes
|
read_file rescue handle_error($!)
|
# good - this catches only the exceptions of Errno::ENOENT class and its descendant classes
|
def foo
|
read_file
|
rescue Errno::ENOENT => e
|
handle_error(e)
|
end
|
----
|
=== Using Exceptions for Flow of Control [[no-exceptional-flows]]
|
Don't use exceptions for flow of control.
|
[source,ruby]
|
----
|
# bad
|
begin
|
n / d
|
rescue ZeroDivisionError
|
puts 'Cannot divide by 0!'
|
end
|
# good
|
if d.zero?
|
puts 'Cannot divide by 0!'
|
else
|
n / d
|
end
|
----
|
=== Blind Rescues [[no-blind-rescues]]
|
Avoid rescuing the `Exception` class.
|
This will trap signals and calls to `exit`, requiring you to `kill -9` the process.
|
[source,ruby]
|
----
|
# bad
|
begin
|
# calls to exit and kill signals will be caught (except kill -9)
|
exit
|
rescue Exception
|
puts "you didn't really want to exit, right?"
|
# exception handling
|
end
|
# good
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.