Skip to content

Commit 8348283

Browse files
committed
Implement Kernel#raise cause parameter
1 parent 26866eb commit 8348283

File tree

3 files changed

+30
-5
lines changed

3 files changed

+30
-5
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ Compatibility:
6060
* Update random implementation layout to be more compatible (#2234).
6161
* Set `RbConfig::CONFIG['LIBPATHFLAG'/'RPATHFLAG']` like MRI to let `$LIBPATH` changes in `extconf.rb` work.
6262
* Access to path and mode via `rb_io_t` from C has been changed to improve compatibility for io-console.
63+
* Implemented `Kernel#raise` `cause` parameter.
6364

6465
Performance:
6566

spec/ruby/core/kernel/raise_spec.rb

+21
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,27 @@
2727

2828
ScratchPad.recorded.should be_nil
2929
end
30+
31+
ruby_version_is "2.6" do
32+
it "accepts a cause keyword argument that sets the cause" do
33+
cause = StandardError.new
34+
-> { raise("error", cause: cause) }.should raise_error(RuntimeError) { |e| e.cause.should == cause }
35+
end
36+
37+
it "accepts a cause keyword argument that overrides the last exception" do
38+
begin
39+
raise "first raise"
40+
rescue => e
41+
cause = StandardError.new
42+
-> { raise("error", cause: cause) }.should raise_error(RuntimeError) { |e| e.cause.should == cause }
43+
end
44+
end
45+
46+
it "raises an ArgumentError when only cause is given" do
47+
cause = StandardError.new
48+
-> { raise(cause: cause) }.should raise_error(ArgumentError)
49+
end
50+
end
3051
end
3152

3253
describe "Kernel#raise" do

src/main/ruby/truffleruby/core/kernel.rb

+8-5
Original file line numberDiff line numberDiff line change
@@ -683,16 +683,19 @@ def warn(*messages, uplevel: undefined)
683683
end
684684
module_function :warn
685685

686-
def raise(exc = undefined, msg = undefined, ctx = nil)
687-
last = $!
688-
if Primitive.undefined?(exc) and last
689-
exc = last
686+
def raise(exc = undefined, msg = undefined, ctx = nil, cause: undefined)
687+
cause_given = !Primitive.undefined?(cause)
688+
cause = cause_given ? cause : $!
689+
690+
if Primitive.undefined?(exc) and cause
691+
raise ArgumentError, 'only cause is given with no arguments' if cause_given
692+
exc = cause
690693
else
691694
exc = Truffle::ExceptionOperations.build_exception_for_raise(exc, msg)
692695

693696
exc.set_backtrace(ctx) if ctx
694697
Primitive.exception_capture_backtrace(exc, 1) unless Truffle::ExceptionOperations.backtrace?(exc)
695-
Primitive.exception_set_cause exc, last unless Primitive.object_equal(exc, last)
698+
Primitive.exception_set_cause exc, cause unless Primitive.object_equal(exc, cause)
696699
end
697700

698701
Truffle::ExceptionOperations.show_exception_for_debug(exc, 1) if $DEBUG

0 commit comments

Comments
 (0)