Capturing multiple exceptions at once in Scala

How to catch several exceptions at once in Scala? Is there a better way than in C #: Capturing multiple exceptions at once?

+55
scala exception exception-handling pattern-matching try-catch
Jun 17 2018-11-11T00:
source share
3 answers

You can bind the entire template to a variable as follows:

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) } 

See Scala Language Specification p. 118, clause 8.1.11 , which are called template alternatives.

+121
Jun 17 '11 at 11:51 on
source share

Since you have access to the full scope of scala pattern matching in the catch clause, you can do a lot:

 try { throw new IOException("no such file") } catch { case _ : SQLException | _ : IOException => println("Resource failure") case e => println("Other failure"); } 

Please note: if you need to write the same handlers over and over again, you can create your own control structure for yourself:

 def onFilesAndDb(code: => Unit) { try { code } catch { your handling code } } 

Some of these methods are available in the scala.util.control.Exceptions object. failing, failAsValue, processing may be exactly what you need

Edit: contrary to what is said below, alternative templates may be related, so the proposed solution is unnecessarily complicated. See Solution @agilesteel

Unfortunately, with this solution you do not have access to the exception where you use alternative patterns. As far as I know, you cannot bind to an alternative template with the e @ (_ : SqlException | _ : IOException) flag e @ (_ : SqlException | _ : IOException) . Therefore, if you need access to the exception, you need to attach sockets:

 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") } 
+25
Jun 17 2018-11-11T00:
source share

You can also use scala.util.control.Exception :

 import scala.util.control.Exception._ import java.io.IOException handling(classOf[RuntimeException], classOf[IOException]) by println apply { throw new IOException("foo") } 

This specific example may not be the best example to illustrate how you can use it, but I find it quite useful in many cases.

+14
Feb 29 '12 at 19:46
source share



All Articles