Is there more elegant way to write:
try {
... // Some throwing code
return first
} catch {
case e:ExceptionType => {} // No code to execute. Ignore error.
}
return second
Is there more elegant way to write:
try {
... // Some throwing code
return first
} catch {
case e:ExceptionType => {} // No code to execute. Ignore error.
}
return second
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 =>
}
scala.util.control.Exception.ignoring(classOf[ExceptionType]) {
... // Some throwing code
}
@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 DefaultTo[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.