E001: Empty Catch Block

This error is emitted when a try expression has a catch block that does not contain any case handlers.

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

def example() =
  try println("hello")
  catch { }

Error

-- [E001] Syntax Error: example.scala:3:2 --------------------------------------
3 |  catch { }
  |  ^^^^^^^^^
  |  The catch block does not contain a valid expression, try
  |  adding a case like - case e: Exception => to the block
  |-----------------------------------------------------------------------------
  | 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 case handler to catch exceptions
import scala.util.control.NonFatal

def example() =
  try println("hello")
  catch { case NonFatal(e) => println(s"Caught: $e") }
// Alternative: use finally instead if you only need cleanup
def example() =
  try println("hello")
  finally println("cleanup")