E002: Empty Catch And Finally Block
This warning is emitted when a try expression has neither a catch block nor a finally block. Such a try is redundant since no exceptions are handled.
A try expression should be followed by some mechanism to handle any exceptions thrown. Typically a catch expression follows the try and pattern matches on any expected exceptions. For example:
try
println("hello")
catch
case e: Exception => ???
It is also possible to follow a try immediately by a finally - letting the exception propagate - but still allowing for some clean up in finally:
try
println("hello")
finally
// perform your cleanup here!
It is recommended to use the NonFatal extractor to catch all exceptions as it correctly handles transfer functions like return.
Example
@main def example() =
try println("hello")
Warning
-- [E002] Syntax Warning: example.scala:2:2 ------------------------------------
2 | try println("hello")
| ^^^^^^^^^^^^^^^^^^^^
| A try without catch or finally is equivalent to putting
| its body in a block; no exceptions are handled.
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| A try expression should be followed by some mechanism to handle any exceptions
| thrown. Typically a catch expression follows the try and pattern matches
| on any expected exceptions. For example:
|
| import scala.util.control.NonFatal
|
| try println("hello") catch {
| case NonFatal(e) => ???
| }
|
| It is also possible to follow a try immediately by a finally - letting the
| exception propagate - but still allowing for some clean up in finally:
|
| try println("hello") finally {
| // perform your cleanup here!
| }
|
| It is recommended to use the NonFatal extractor to catch all exceptions as it
| correctly handles transfer functions like return.
-----------------------------------------------------------------------------
Solution
// Remove redundant 'try' block
def example() =
println("hello")
// Alternative: Add a catch block to handle exceptions
import scala.util.control.NonFatal
def example() =
try
println("hello")
catch
case NonFatal(e) => println(s"Caught: $e")
// Alternative: Add a finally block for cleanup
def example() =
try
println("hello")
finally
println("cleanup")
In this article