Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching multiple exception types to the same case

Tags:

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?

like image 266
Josh Avatar asked Dec 12 '11 22:12

Josh


People also ask

How do you handle multiple exceptions?

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.

Can you throw multiple exceptions in one throw statement?

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) { // ... }

How do you handle multiple exceptions in single catch block?

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.

Is there a way to catch multiple exceptions at once and without code duplication?

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.


1 Answers

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 
like image 182
Ben James Avatar answered Sep 30 '22 05:09

Ben James