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?
By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.
You can't throw two exceptions. I.e. you can't do something like: try { throw new IllegalArgumentException(), new NullPointerException(); } catch (IllegalArgumentException iae) { // ... } catch (NullPointerException npe) { // ... }
If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.
Catching multiple exceptions at once using switch-case In this approach, we catch all the exceptions inside a single catch block using the switch-case statement.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With