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") }
Didier Dupont Jun 17 2018-11-11T00: 00Z
source share