35

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
0

4 Answers 4

47
scala.util.control.Exception.ignoring(classOf[ExceptionType]) {
  ... // Some throwing code
}
Sign up to request clarification or add additional context in comments.

1 Comment

How to do in case the throwing code has to return a value?
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.

1 Comment

BTW it could be written a bit shorter with handling(classOf[NumberFormatException]).by(_ => 0) { "Hi".toInt }
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 => 
}

Comments

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.

4 Comments

What do you mean by non-fatal exceptions?
Have a look at the source for Try, it calls NonFatal, which considers VirtualMachineError, ThreadDeath, InterruptedException, LinkageError and ControlThrowable to be fatal
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)=>}
you're confusing try with Try - which is the main problem with this method of ignoring exceptions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.