Skip to content

Instantly share code, notes, and snippets.

@mrchrisadams
Created January 27, 2012 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrchrisadams/1688271 to your computer and use it in GitHub Desktop.
Save mrchrisadams/1688271 to your computer and use it in GitHub Desktop.
How can I see which exception was raised in the rescue block in this method?
def some_method
# some stuff in ruby that might fail
rescue
# do stuff, like drop into pry, with binding.pry, or ruby-debug with debugger to inspect
# state for debugging
end
@spatchcock
Copy link

def divide_thousand_by_number(n)
1000 / n
rescue => error
puts error.class
end

divide_thousand_by_number(1)
=> 1000
divide_thousand_by_number(0)
=> ZeroDivisionError

@mrchrisadams
Copy link
Author

Ah, thanks Andrew,

I didn't know about the => error part inside a method. That's exactly what I was looking for !

BTW, I came across this when asking in #rubylang on freenode.net

https://github.com/pry/pry-stack_explorer

Handy huh?

@MrJaba
Copy link

MrJaba commented Jan 27, 2012

You always have access to the last exception thrown in the variable $! as well.

@MrJaba
Copy link

MrJaba commented Jan 27, 2012

But in regards to the => error, be careful with this, blanket catching exceptions isn't a great idea. Add more specific rescue clauses with the exception types, for example:

rescue ZeroDivisionError => e
handle_divide_by_zero

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment