text
stringlengths
0
444
----
== Exceptions
=== `raise` vs `fail` [[prefer-raise-over-fail]]
Prefer `raise` over `fail` for exceptions.
[source,ruby]
----
# bad
fail SomeException, 'message'
# good
raise SomeException, 'message'
----
=== Raising Explicit `RuntimeError` [[no-explicit-runtimeerror]]
Don't specify `RuntimeError` explicitly in the two argument version of `raise`.
[source,ruby]
----
# bad
raise RuntimeError, 'message'
# good - signals a RuntimeError by default
raise 'message'
----
=== Exception Class Messages [[exception-class-messages]]
Prefer supplying an exception class and a message as two separate arguments to `raise`, instead of an exception instance.
[source,ruby]
----
# bad
raise SomeException.new('message')
# Note that there is no way to do `raise SomeException.new('message'), backtrace`.
# good
raise SomeException, 'message'
# Consistent with `raise SomeException, 'message', backtrace`.
----
=== `return` from `ensure` [[no-return-ensure]]
Do not return from an `ensure` block.
If you explicitly return from a method inside an `ensure` block, the return will take precedence over any exception being raised, and the method will return as if no exception had been raised at all.
In effect, the exception will be silently thrown away.
[source,ruby]
----
# bad
def foo
raise
ensure
return 'very bad idea'
end
----
=== Implicit `begin` [[begin-implicit]]
Use _implicit begin blocks_ where possible.
[source,ruby]
----
# bad
def foo
begin
# main logic goes here
rescue
# failure handling goes here
end
end
# good
def foo
# main logic goes here
rescue
# failure handling goes here
end
----
=== Contingency Methods [[contingency-methods]]
Mitigate the proliferation of `begin` blocks by using _contingency methods_ (a term coined by Avdi Grimm).
[source,ruby]
----
# bad
begin
something_that_might_fail
rescue IOError
# handle IOError
end
begin
something_else_that_might_fail
rescue IOError