Some such methods are available in object scala.util.control.Exceptions. failing, failAsValue, handling may be just what you need
Edit : Contrary to what is said below, alternative patterns can be bound, so the proposed solution is needlessly complex. See @agilesteel solution
Unfortunately, with this solution, you have no access to the exception where you use the alternative patterns. To my knowledge, you cannot bind on an alternative pattern with case e @ (_ : SqlException | _ : IOException). So if you need access to the exception, you have to nest matchers :
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")
}
You can bind the whole pattern to a variable like this:
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)
}
This was the only way for me, which passed trough the sbt clean coverage test coverageReport without throwing the nasty parsing exception ...
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)
Scala version 3 (released in 2021) supports union types, which creates another solution to the already mentioned solutions, although it looks very very similar, but it's different:
(For comparison, I've used the code from solution https://stackoverflow.com/a/6385333/1039774 from 2011, and changed it to Scala 3 with union types, and the new operator can be omitted in Scala 3.)
try {
throw IOException("no such file")
} catch {
// prints out "java.io.IOException: no such file"
case e: (RuntimeException | IOException) => println(e)
}