Bug #15558

Should Exception#exception copy the backtrace?

Added by Eregon (Benoit Daloze) 7 months ago. Updated 21 days ago.

Target version:
ruby -v:
ruby 2.6.0p0 (2018-12-25 revision 66547) [x86_64-linux]


Currently it does not on MRI:

ruby -e 'begin raise "foo"; rescue => e; c=e.exception "bar"; p c.backtrace; end'

But it does on JRuby and TruffleRuby 1.0.0-rc11:

truffleruby -e 'begin raise "foo"; rescue => e; c=e.exception "bar"; p e.backtrace; end'
["-e:1:in `<main>'"]

This means in some cases, code needs about this difference such as in
More context in:


Updated by Eregon (Benoit Daloze) 5 months ago

nobu (Nobuyoshi Nakada) and other MRI committers: what do you think?

It's somewhat inconsistent with Exception#clone which does copy the backtrace.

Would it make sense to follow JRuby and TruffleRuby's behavior, by copying the backtrace too, here?

Updated by Eregon (Benoit Daloze) 5 months ago

BTW, MRuby 2.0.0 also copies the backtrace (because it implements Exception#exception as clone + setting the message):

$ mruby -e 'begin raise "foo"; rescue => e; c=e.exception "bar"; p c.backtrace; end'          

MRI also clones (with rb_obj_clone), but exc_init resets the backtrace to nil.
So should exc_exception() just call rb_ivar_set(exc, id_mesg, argv[0]); instead of exc_initialize (which kind of initializes the object twice)?

Updated by Eregon (Benoit Daloze) 3 months ago

I plan to fix this and copy the backtrace too in MRI, because it looks not intentional and inconsistent.
Anyone against?

Updated by Eregon (Benoit Daloze) 2 months ago

  • Assignee set to Eregon (Benoit Daloze)

Updated by ko1 (Koichi Sasada) 21 days ago

I'm not sure the intention, but

Japanese document shows how to use it:

 ...        # do something
rescue => e
 raise e.exception("an error occurs during hogehoge process")  # detailed message

If this method is intended to be raised immediately, the empty backtrace is reasonable.

Also available in: Atom PDF