Skip to content

Commit

Permalink
raise(Exception): Setup callstack on raise only if not already set. F…
Browse files Browse the repository at this point in the history
…ixes #4482.

It's useful for reraising of exceptions in `rescue` blocks.

As proposed by #4482 (comment).

/cc @asterite, @straight-shoota.
  • Loading branch information
akzhan committed May 30, 2017
1 parent a8b9336 commit b357676
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
25 changes: 25 additions & 0 deletions spec/std/raise_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
require "spec"

struct CallStack # allow clone and equality
def_clone
def_equals @callstack
end

describe "raise" do
it "should throw exception with existing callstack if already set" do
ex = Exception.new "with callstack"
ex.callstack = CallStack.new
callstack_to_match = ex.callstack.clone
new_ex = expect_raises Exception, "with callstack" do
raise ex
end
new_ex.callstack.should eq(callstack_to_match)
end

it "should throw exception with new callstack if not already set" do
new_ex = expect_raises Exception, "without callstack" do
raise Exception.new("without callstack")
end
new_ex.callstack.should_not be_nil
end
end
13 changes: 9 additions & 4 deletions src/raise.cr
Original file line number Diff line number Diff line change
Expand Up @@ -175,16 +175,21 @@ fun __crystal_get_exception(unwind_ex : LibUnwind::Exception*) : UInt64
unwind_ex.value.exception_object
end

def raise(ex : Exception) : NoReturn
ex.callstack = CallStack.new
# Raises the *exception*.
#
# Note that exception callstack will only be set if it's not already set.
# It's useful for reraising of exceptions in `rescue` blocks.
def raise(exception : Exception) : NoReturn
exception.callstack ||= CallStack.new
unwind_ex = Pointer(LibUnwind::Exception).malloc
unwind_ex.value.exception_class = LibC::SizeT.zero
unwind_ex.value.exception_cleanup = LibC::SizeT.zero
unwind_ex.value.exception_object = ex.object_id
unwind_ex.value.exception_type_id = ex.crystal_type_id
unwind_ex.value.exception_object = exception.object_id
unwind_ex.value.exception_type_id = exception.crystal_type_id
__crystal_raise(unwind_ex)
end

# Raises an Exception with the *message*.
def raise(message : String) : NoReturn
raise Exception.new(message)
end
Expand Down

0 comments on commit b357676

Please sign in to comment.