2016-09-10 3 views
1

このコードは "I've failed"を例外として返します。Scala試してみて、違う失敗例

Try({ 
    throw new Exception() 
    }) match { 
    case Failure(e) => println("I've failed") 
    case Success(s) => println("I've succeeded") 
    } 

しかし、私のようなさまざまな例外、持っている場合:

Try({ 
    if(someBoolean) { 
     throw new DifferentException() 
    } else { 
     throw new Exception() 
    } 
    }) match { 
    case Failure(e) => println("I've failed") 
    case Success(s) => println("I've succeeded") 
    } 

を我々はExceptionDifferentExceptionに異なる場合がありますように、私は一致ステートメントを変更するにはどうすればよいですか?

私はこれを行うことができます理解:

Try({ 
    if(true) { 
     throw new DifferentException() 
    } else { 
     throw new Exception() 
    } 
    }) match { 
    case Failure(e) if e.isInstanceOf[DifferentException] => println("I've failed differently") 
    case Failure(e) if e.isInstanceOf[Exception]   => println("I've failed") 
    case Success(s) => println("I've succeeded") 
    } 

は、このようなを達成するための最良の、すなわち少なくとも冗長、方法は何ですか?

[編集]

アシェットありがとうございます。少なくとも冗長、私にとっては、これだった:

case class DifferentException() extends Exception() {} 

Try({ 
    if(someBoolean) { 
    throw new DifferentException 
    } else { 
    throw new Exception 
    } 
}) match { 
    case Failure(DifferentException()) => println("I've failed differently") 
    case Failure(e)     => println("I've failed") 
    case Success(s)     => println("I've succeeded") 
} 

答えて

1

あなたはcase class例外に一致させることができますいいえ。

case class ExceptionOne(msg: String) extends Exception(msg)など。

そして、

Try { /* ...*/ } match { 
    case Failure(ExceptionOne(msg)) => println("exception of type 1") 
    // more cases 
    case Failure(e) => println("generic exception") 
    case Success(s) => ??? 
} 

また、1つのFailureで一致して、それに含まれる例外をマッチさせることができます。

Try { /* ...*/ } match { 
    case Failure(e) => e match { 
    case e1: DifferentException => // do something with DifferentException 
    case e: Exception => // do something with a generic exception 
    } 
    case Success(s) => ??? 
} 
+1

はありがとうございます。結局、前者が最高だった。 – newfivefour

6

あなたはどの例外タイプ(ケースクラスまたはしない)、独自の例外の種類または2つのパターンマッチング式を作成する必要はありませんためFailure(e: ExceptionType)を一致させることができます:

def printResult(action: => Unit) = { 
    Try(action) match { 
    case Failure(e: IllegalArgumentException) => println("illegal arg exception") 
    case Failure(e) => println("other exception") 
    case _ => println("success") 
    } 
} 

printResult(throw new IllegalArgumentException) // prints "illegal arg exception" 
printResult(throw new RuntimeException)   // prints "other exception" 
printResult(1)         // prints "success" 
+0

この場合、カスタム例外はプログラムにとっては良いことですが、これは優れた第3の方法です。ありがとう。 – newfivefour

関連する問題