Thursday, September 3, 2009

Exception handling

In Scala exceptions are not checked so effectively all exceptions are runtime exceptions. When you want to handle exceptions you use a try {...} catch {...} block like you would in Java except that the catch block uses matching to identify and handle the exceptions. This creates a very powerful but light-weight way to handle exceptions:

  1. scala>def handle( f: => Unit ) = {
  2.      | try { f } catch {
  3.      | case _:AssertionError => println ("Whoops an assertion error")
  4.      | case r:RuntimeException => println ("Runtime Exception: "+ r.getStackTraceString)
  5.      | case e if (e.getMessage == null) => println ("Unknown exception with no message")
  6.      | case e => println ("An unknown error has been caught" + e.getMessage)
  7.      | }
  8.      | }
  9. handle: (=> Unit)Unit
  10. scala> handle { throw new AssertionError("big bad error") }
  11. Whoops an assertion error
  12. scala> handle { throw new IllegalArgumentException("Sooooo illegal") }
  13. Runtime Exception: line9$object$$iw$$iw$$iw$$anonfun$1.apply(:8)
  14. line9$object$$iw$$iw$$iw$$anonfun$1.apply(:8)
  15. line7$object$$iw$$iw$$iw$.handle(:7)
  16. line9$object$$iw$$iw$$iw$.(:8)
  17. line9$object$$iw$$iw$$iw$.()
  18. RequestResult$line9$object$.(:3)
  19. RequestResult$line9$object$.()
  20. RequestResult$line9$object.result()
  21. sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  22. sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  23. sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  24. java.lang.reflect.Method.invoke(Method.java:597)
  25. scala.tools.nsc.Interpreter$Request.loadAndRun(Interpreter.scala:889)
  26. scala.tools.nsc.Interpreter.interpret(Interpreter.scala:508)
  27. scala.tools.nsc.Interpreter.interpret(Interpreter.scala:494)
  28. scala.tools.nsc.InterpreterLoop.interpretStartingWith(InterpreterLoop.scala:242)
  29. scala.tools.nsc.InterpreterLoop.command(InterpreterLoop.scala:230)
  30. scala.tools.nsc.InterpreterLoop.repl(InterpreterLoop.scala:142)
  31. scala.tools.nsc.InterpreterLoop.main(InterpreterLoop.scala:298)
  32. scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:141)
  33. scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
  34. scala> handle{ throw new java.io.IOException("cant read something") }
  35. An unknown error has been caughtcant read something

No comments:

Post a Comment