Reputation: 875
When pattern matching an exception with a case statement, is there a more simplified way of matching the same exception to a set of exception types? Instead of this:
} catch {
case e if e.isInstanceOf[MappingException] || e.isInstanceOf[ParseException] =>
Something like this would be nice:
case e: MappingException | ParseException | SomeOtherException =>
Is something like this possible?
Upvotes: 21
Views: 6921
Reputation: 125167
You can do this:
catch {
case e @ (_: MappingException | _: ParseException | _: SomeOtherException) =>
}
If you're trying to save some lines of code and you handle the same types of exceptions regularly, you might consider defining a partial function beforehand to use as a handler:
val myHandler: PartialFunction[Throwable, Unit] = {
case e @ (_: MappingException | _: ParseException | _: SomeOtherException) =>
}
try {
throw new MappingException("argh!")
} catch myHandler
Upvotes: 52