E002: 빈 Catch와 Finally 블록

E002: 빈 Catch와 Finally 블록 (Empty Catch And Finally Block)

이 경고는 try 표현식에 catch 블록도 finally 블록도 없을 때 발생해요. 예외를 처리하는 게 하나도 없으니 그런 try는 사실상 불필요하죠.

출처: Scala 3 Reference

본문

try 표현식 뒤에는 던져진 예외를 처리할 어떤 메커니즘이 따라와야 해요. 보통은 try 뒤에 catch 표현식이 붙어서 예상되는 예외를 패턴 매칭하죠. 예를 들어:

try
  println("hello")
catch
  case e: Exception => ???

try를 바로 finally로 이어서 — 예외는 그대로 전파되게 하되 finally에서 정리(cleanup)를 수행하게 할 수도 있어요:

try
  println("hello")
finally
  // perform your cleanup here!

모든 예외를 잡을 때는 NonFatal 추출기를 쓰는 걸 권장해요. return 같은 전송 함수(transfer function)를 올바르게 처리해 주니까요.

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")

더 알아보기

  • try/catch/finally의 올바른 사용법은 E001 문서와 함께 보면 좋아요.