E001: 빈 Catch 블록
E001: 빈 Catch 블록 (Empty Catch Block)
이 에러는 try 표현식의 catch 블록에 어떤 case 핸들러도 들어 있지 않을 때 발생해요.
본문
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
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")
더 알아보기
NonFatal추출기와 예외 처리 전반에 대해서는scala.util.control패키지 문서를 살펴보세요.