34

Is there more elegant way to write the following?

try {
    ... // Some throwing code
    return first
} 
catch {
    case e:ExceptionType => {} // No code to execute. Ignore error.
}
return second
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Basilevs
  • 22,440
  • 15
  • 57
  • 102

4 Answers4

46
scala.util.control.Exception.ignoring(classOf[ExceptionType]) {
  ... // Some throwing code
}
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
18

@Daniel has already provided the canonical method to use to do this. Look through the other methods in scala.util.control.Exception--they are quite helpful and generic!

If you need to get a return value out of the try block, use failing instead of ignoring (but be aware that the result is an Any, i.e. not typesafe).

You can also write your own exception-catcher, which will be a little slow for heavy-duty work but otherwise nice to use:

class DefaultOn[E <: Exception] {
  def apply[A](default: => A)(f: => A)(implicit m: Manifest[E]) = {
    try { f } catch { case x if (m.erasure.isInstance(x)) => default }
  }
}
object DefaultOn { def apply[E <: Exception] = new DefaultOn[E] }

scala> DefaultOn[NumberFormatException](0) { "Hi".toInt }
res0: Int = 0

Or if you like options:

class TryOption[E <: Exception] {
  def apply[A](f: => A)(implicit m: Manifest[E]) = {
    try { Some(f) } catch { case x if (m.erasure.isInstance(x)) => None }
  }
}
object TryOption { def apply[E <: Exception] = new TryOption[E] }

scala> TryOption[NumberFormatException] { "Hi".toInt }
res1: Option[Int] = None

Or you can be inspired by this plus the library routines and create your own methods to ignore multiple different exceptions and preserve types on the return value.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • BTW it could be written a bit shorter with `handling(classOf[NumberFormatException]).by(_ => 0) { "Hi".toInt }` – Qrilka Feb 21 '11 at 20:16
5

In Scala all exceptions are not checked, so if you don't want, you may just skip handling them (and thus exception will be escalated to a higher level). Silently ignoring an exception the way you want to do is generally a bad practice. However, your code can be shortened to:

try {
  ... // Some throwing code
} catch {
  case e:ExceptionType => 
}
Vasil Remeniuk
  • 20,519
  • 6
  • 71
  • 81
2

Hows about:

Try { 
     // some throwing code 
}

This will ignore all non fatal exceptions, which is what you want to do most of the time.

jonathanChap
  • 799
  • 7
  • 7
  • What do you mean by non-fatal exceptions? – Basilevs Apr 06 '17 at 10:22
  • Have a look at the source for Try, it calls NonFatal, which considers VirtualMachineError, ThreadDeath, InterruptedException, LinkageError and ControlThrowable to be fatal – jonathanChap Apr 07 '17 at 05:55
  • This is not accurate. As of Scala 2.11, this would give a warning at compile time: "A try without a catch or finally is equivalent to putting its body in a block; no exceptions are handled." Indeed, it is identical to not using the Try at all. You have to add a catch to catch NonFatal exceptions, ie catch{case NonFatal(e)=>} – TaylerJones Jul 28 '17 at 21:55
  • 1
    you're confusing try with Try - which is the main problem with this method of ignoring exceptions – jonathanChap Jul 31 '17 at 09:39