2

Experimenting with Scala... I'm trying to define something analogous to the "@" hack in PHP (which means, ignore any exception in the following statement).

I managed to get a definition that works:

    def ignoreException(f: () => Unit) = {
      try {
        f();
      }
      catch {
        case e: Exception => println("exception ignored: " + e);
      }
    }

And use it like this:

ignoreException( () => { someExceptionThrowingCodeHere() } );

Now here is my question... Is there anyway I can simplify the usage and get rid of the () =>, and maybe even the brackets?

Ultimately I'd like the usage to be something like this:

`@` { someExceptionThrowingCodeHere(); }

2 Answers 2

12

@ is reserved in Scala (for pattern matching), but would you accept @@?

scala> def @@(block: => Unit): Unit = try {
  block
} catch {
  case e => printf("Exception ignored: %s%n", e)
}   
$at$at: (=> Unit)Unit

scala> @@ {
  println("before exception")
  throw new RuntimeException()
  println("after exception")
}
before exception
Exception ignored: java.lang.RuntimeException

I'm not convinced this is a good idea, however ☺

Sign up to request clarification or add additional context in comments.

Comments

6

You don't have to use a function as your parameter, a "by-name" parameter will do:

def ignoreException(f: =>Unit) = {
  try {
    f
  }
  catch {
    case e: Exception => println("exception ignored: " + e)
  }
}

ignoreException(someExceptionThrowingCodeHere())

Eric.

1 Comment

Note the the calling code could be written in the same style that Alex R showed as a usage example: ignoreException { blah(); blah() }

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.