Skip to content

Commit

Permalink
SI-7110 Warn about naked try without catch/finally
Browse files Browse the repository at this point in the history
Before, this was allowed:

    scala> try ( 1 / 0 )
    java.lang.ArithmeticException: / by zero

But since the advent of util.Try, the subtle difference to the
following seems dangerous:

    scala> import util.Try
    import util.Try

    scala> Try ( 1 / 0 )
    res4: scala.util.Try[Int] = Failure(java.lang.ArithmeticException: / by zero)

Discussion: https://groups.google.com/d/topic/scala-language/fy2vXD_3fF8/discussion

There was some concern that this curtails a handy, temporary
way to remove the exception handlers from some code. But after
thinking about this, I contend that:

 a) those people can easily stomach the warning temporarily
    (modulo, of course, those with -Xfatal-warnings.)
 b) putting this warning behind Xlint will disable it for those
    who need it most: beginners.

I also chose not to refer to 'scala.util.Try' in the error message
as I think that has as much potential to confuse as it does to clarify.
  • Loading branch information
retronym committed Mar 29, 2013
1 parent 1debc74 commit 530f4a5
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/compiler/scala/tools/nsc/typechecker/Typers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4993,6 +4993,13 @@ trait Typers extends Adaptations with Tags {
}

def typedTry(tree: Try) = {
tree match {
case Try(_, Nil, EmptyTree) =>
if (!isPastTyper) context.warning(tree.pos,
"A try without a catch or finally is equivalent to putting its body in a block; no exceptions are handled.")
case _ =>
}

var block1 = typed(tree.block, pt)
var catches1 = typedCases(tree.catches, ThrowableClass.tpe, pt)

Expand Down
6 changes: 6 additions & 0 deletions test/files/neg/t7110.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
t7110.scala:2: warning: A try without a catch or finally is equivalent to putting its body in a block; no exceptions are handled.
try { ??? } // warn
^
error: No warnings can be incurred under -Xfatal-warnings.
one warning found
one error found
1 change: 1 addition & 0 deletions test/files/neg/t7110.flags
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
-Xfatal-warnings
6 changes: 6 additions & 0 deletions test/files/neg/t7110.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
object Test {
try { ??? } // warn

try { ??? } finally ??? // no warn
try { ??? } catch { case _: Throwable => } // no warn
}

0 comments on commit 530f4a5

Please sign in to comment.