Skip to content

Commit ced58fc

Browse files
author
Ary Borenszweig
committedFeb 14, 2017
Fixed #4030: Can't catch TypeCastError when doing as inside method
1 parent 69cd7c8 commit ced58fc

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed
 

Diff for: ‎spec/compiler/codegen/exception_spec.cr

+18
Original file line numberDiff line numberDiff line change
@@ -1255,4 +1255,22 @@ describe "Code gen: exception" do
12551255
print 5
12561256
)).to_i.should eq(123)
12571257
end
1258+
1259+
it "catches exception thrown by as inside method (#4030)" do
1260+
run(%(
1261+
require "prelude"
1262+
1263+
def foo
1264+
a = 1 || ""
1265+
a.as(String)
1266+
end
1267+
1268+
begin
1269+
foo
1270+
"bad"
1271+
rescue ex : TypeCastError
1272+
"good"
1273+
end
1274+
)).to_string.should eq("good")
1275+
end
12581276
end

Diff for: ‎src/compiler/crystal/semantic/main_visitor.cr

+6
Original file line numberDiff line numberDiff line change
@@ -1696,6 +1696,12 @@ module Crystal
16961696
end
16971697

16981698
def visit(node : Cast | NilableCast)
1699+
# If there's an `x.as(T)` inside a method, that method
1700+
# has a chance to raise, so we must mark it as such
1701+
if typed_def = @typed_def
1702+
typed_def.raises = true
1703+
end
1704+
16991705
node.obj.accept self
17001706

17011707
@in_type_args += 1

0 commit comments

Comments
 (0)
Please sign in to comment.