Skip to content

Commit 13a8b9f

Browse files
oderskyolsdavis
authored andcommitted
Disallow throws clauses over RuntimeExceptions
Fixes scala#13846
1 parent 481dfb1 commit 13a8b9f

File tree

3 files changed

+35
-3
lines changed

3 files changed

+35
-3
lines changed

compiler/src/dotty/tools/dotc/typer/Typer.scala

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1942,14 +1942,20 @@ class Typer extends Namer
19421942
}
19431943
var checkedArgs = preCheckKinds(args1, paramBounds)
19441944
// check that arguments conform to bounds is done in phase PostTyper
1945-
if (tpt1.symbol == defn.andType)
1945+
val tycon = tpt1.symbol
1946+
if (tycon == defn.andType)
19461947
checkedArgs = checkedArgs.mapconserve(arg =>
19471948
checkSimpleKinded(checkNoWildcard(arg)))
1948-
else if (tpt1.symbol == defn.orType)
1949+
else if (tycon == defn.orType)
19491950
checkedArgs = checkedArgs.mapconserve(arg =>
19501951
checkSimpleKinded(checkNoWildcard(arg)))
1952+
else if tycon == defn.throwsAlias
1953+
&& checkedArgs.length == 2
1954+
&& checkedArgs(1).tpe.derivesFrom(defn.RuntimeExceptionClass)
1955+
then
1956+
report.error(em"throws clause cannot be defined for RuntimeException", checkedArgs(1).srcPos)
19511957
else if (ctx.isJava)
1952-
if (tpt1.symbol eq defn.ArrayClass) then
1958+
if tycon eq defn.ArrayClass then
19531959
checkedArgs match {
19541960
case List(arg) =>
19551961
val elemtp = arg.tpe.translateJavaArrayElementType

tests/neg/i13846.check

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
-- Error: tests/neg/i13846.scala:3:22 ----------------------------------------------------------------------------------
2+
3 |def foo(): Int throws ArithmeticException = 1 / 0 // error
3+
| ^^^^^^^^^^^^^^^^^^^
4+
| throws clause cannot be defined for RuntimeException
5+
-- Error: tests/neg/i13846.scala:7:9 -----------------------------------------------------------------------------------
6+
7 | foo() // error
7+
| ^
8+
| The capability to throw exception ArithmeticException is missing.
9+
| The capability can be provided by one of the following:
10+
| - A using clause `(using CanThrow[ArithmeticException])`
11+
| - A `throws` clause in a result type such as `X throws ArithmeticException`
12+
| - an enclosing `try` that catches ArithmeticException
13+
|
14+
| The following import might fix the problem:
15+
|
16+
| import unsafeExceptions.canThrowAny
17+
|

tests/neg/i13846.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import language.experimental.saferExceptions
2+
3+
def foo(): Int throws ArithmeticException = 1 / 0 // error
4+
5+
def test(): Unit =
6+
try
7+
foo() // error
8+
catch
9+
case _: ArithmeticException => println("Caught")

0 commit comments

Comments
 (0)