E235: Unreasonable Catch
This warning is emitted when you write a catch case that can catch Error.
Catching Errors, including by catching all Throwables, can lead to unexpected behavior because an ${hl("Error")} being thrown indicates an unrecoverable problem.
The JDK documentation states that "a reasonable application should not try to catch" Error. The JDK has had a number of bugs around expected behavior when an Error is caught, such as finally blocks not executing (source) and locks remaining locked (source).
On some platforms such as Scala.js, such errors will immediately terminate the application and cannot be caught.
Example
def foo(): Unit = ???
def bar(): Unit =
try foo()
catch case t: Throwable => ???
Error
-- [E235] Potential Issue Warning: example.scala:5:16 --------------------------
5 | catch case t: Throwable => ???
| ^^^^^^^^^
| Catching Throwable can lead to unexpected behavior
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Catching Error subclasses, including by catching all Throwables,
| can lead to unexpected behavior because an Error being thrown indicates
| an unrecoverable problem.
| The JDK documentation states that "a reasonable application should not
| try to catch" Errors, and on some platforms such as Scala.js,
| such errors will immediately terminate the application and cannot be caught.
-----------------------------------------------------------------------------
Solution
Use NonFatal from scala.util.control to only catch non-fatal throwables:
import scala.util.control.NonFatal
def foo(): Unit = ???
def bar(): Unit =
try foo()
catch case NonFatal(t) => ???
In this article