Skip to content

Commit

Permalink
Fixed #4030: Can't catch TypeCastError when doing as inside method
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Feb 14, 2017
1 parent 69cd7c8 commit ced58fc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
18 changes: 18 additions & 0 deletions spec/compiler/codegen/exception_spec.cr
Expand Up @@ -1255,4 +1255,22 @@ describe "Code gen: exception" do
print 5
)).to_i.should eq(123)
end

it "catches exception thrown by as inside method (#4030)" do
run(%(
require "prelude"
def foo
a = 1 || ""
a.as(String)
end
begin
foo
"bad"
rescue ex : TypeCastError
"good"
end
)).to_string.should eq("good")
end
end
6 changes: 6 additions & 0 deletions src/compiler/crystal/semantic/main_visitor.cr
Expand Up @@ -1696,6 +1696,12 @@ module Crystal
end

def visit(node : Cast | NilableCast)
# If there's an `x.as(T)` inside a method, that method
# has a chance to raise, so we must mark it as such
if typed_def = @typed_def
typed_def.raises = true
end

node.obj.accept self

@in_type_args += 1
Expand Down

0 comments on commit ced58fc

Please sign in to comment.