Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why raise an exception with the current method removed from the stack trace?

Tags:

exception

ruby

When raising a Ruby exception, I understand I can use the caller method to generate the backtrace that removes the current method call:

raise SomeException, "error message", caller

According to the pickaxe book, this is "often useful in library modules".

Why would you want to remove the current method from the stack trace? It seems like the more information I can have about exactly where the error occurred, the easier it would be to track down.

like image 345
Jeff Storey Avatar asked Sep 12 '25 11:09

Jeff Storey


1 Answers

The reason that seems useful to me is so that the stack trace can most clearly point the user of the library to the source of the problem. My copy of Programming Ruby didn't provide any more insight than yours did, but The Ruby Programming Language confirms my feelings with this:

The intent of the exception we're raising here is to point out a problem with the invocation of the ... method, not with the code inside the method. ... If we want to point directly to the problem code, we can provide a custom stack trace as the third argument to raise with ... caller.

like image 167
Darshan Rivka Whittle Avatar answered Sep 14 '25 23:09

Darshan Rivka Whittle