Development Tip

Scala에서 한 번에 여러 예외 잡기

yourdevel 2020. 11. 9. 21:18
반응형

Scala에서 한 번에 여러 예외 잡기


Scala에서 한 번에 여러 예외를 포착하는 방법은 무엇입니까? C #보다 더 좋은 방법이 있습니까? 한 번에 여러 예외를 포착합니까?


전체 패턴을 다음과 같이 변수에 바인딩 할 수 있습니다.

try {
   throw new java.io.IOException("no such file")
} catch {
   // prints out "java.io.IOException: no such file"
   case e @ (_ : RuntimeException | _ : java.io.IOException) => println(e)
}

참조 스칼라 언어 사양 페이지 (118) 제 8.1.11 라는 패턴 대안을.

Scala의 패턴 매칭에 대해 자세히 알아 보려면 Pattern Matching Unleashed시청 하세요.


catch 절에서 scala의 전체 패턴 일치 기능에 액세스 할 수 있으므로 많은 작업을 수행 할 수 있습니다.

try {
  throw new IOException("no such file")
} catch {
  case _ : SQLException | _ : IOException => println("Resource failure")
  case e => println("Other failure");
}

동일한 처리기를 반복해서 작성해야하는 경우이를위한 고유 한 제어 구조를 만들 수 있습니다.

def onFilesAndDb(code: => Unit) { 
  try { 
    code 
  } catch {
    your handling code 
  }
}

이러한 메서드 중 일부는 scala.util.control.Exceptions 개체에서 사용할 수 있습니다 . failing, failAsValue, 처리는 필요한 것일 수 있습니다.

편집 : 아래에 언급 된 것과 달리 대체 패턴이 바인딩 될 수 있으므로 제안 된 솔루션은 불필요하게 복잡합니다. @agilesteel 솔루션보기

불행히도이 솔루션을 사용하면 대체 패턴을 사용하는 예외에 액세스 할 수 없습니다. 내가 아는 한, 당신은 case로 대체 패턴을 묶을 수 없습니다 e @ (_ : SqlException | _ : IOException). 따라서 예외에 대한 액세스가 필요하면 매처를 중첩해야합니다.

try {
  throw new RuntimeException("be careful")
} catch  {
  case e : RuntimeException => e match {
    case _ : NullPointerException | _ : IllegalArgumentException => 
      println("Basic exception " + e)
    case a: IndexOutOfBoundsException => 
      println("Arrray access " + a)
    case _ => println("Less common exception " + e)
  }
  case _ => println("Not a runtime exception")
}

다음을 사용할 수도 있습니다 scala.util.control.Exception.

import scala.util.control.Exception._
import java.io.IOException

handling(classOf[RuntimeException], classOf[IOException]) by println apply { 
  throw new IOException("foo") 
}

이 특정 예는 사용 방법을 설명하는 가장 좋은 예가 아닐 수 있지만 많은 경우에 매우 유용합니다.


이것은 sbt clean coverage test coverageReport불쾌한 파싱 예외를 던지지 않고 통과 한 유일한 방법이었습니다 ...

try {
   throw new CustomValidationException1( 
      CustomErrorCodeEnum.STUDIP_FAIL,
      "could be throw new CustomValidationException2")
    } catch {
    case e
      if (e.isInstanceOf[CustomValidationException1] || e
      .isInstanceOf[CustomValidationException2]) => {
        // run a common handling for the both custom exceptions
        println(e.getMessage)
        println(e.errorCode.toString) // an example of common behaviour 
    }
    case e: Exception => {
      println("Unknown error occurred while reading files!!!")
      println(e.getMessage)
      // obs not errorCode available ...
    }
}

    // ... 
    class CustomValidationException1(val errorCode: CustomErrorCodeEnum, val message: String)
    class CustomValidationException2(val errorCode: CustomErrorCodeEnum, val message: String)

참고 URL : https://stackoverflow.com/questions/6384073/catching-multiple-exceptions-at-once-in-scala

반응형