Showing posts with label try. Show all posts
Showing posts with label try. Show all posts

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

Monday, August 17, 2009

Return values

As with most functional languages, most control structures ( if, for, try ) return values. The common java idiom:
  1. String name=null;
  2. if( xxx ) name="yyy";
  3. else name="zzz";

can be replaced by
  1. val name = if( xxx ) "yyy"; else"zzz";

The benefit (other than less boiler plate code) is that name can now be a val instead of a var.

Another other point about returns: The return keyword is not required when returning a value from methods or control structures. The last value is always the return value. This is why you will get an error if the last line in a method or control structure is an assignment.

Examples:
  1. scala>val name = if( 1==2 ) "Jesse"else"Mauricio"
  2. name: java.lang.String = Mauricio
  3. scala> println(name)
  4. Mauricio
  5. scala>val collection = for( i <- 1 to 100; if(i%20 == 3) ) yield i
  6. collection: Seq.Projection[Int] = RangeFM(3, 23, 43, 63, 83)
  7. scala> collection.foreach( i => print( i +" ") )
  8. 3 23 43 63 83
  9. scala>val someObj:AnyRef = "Hello"
  10. someObj: AnyRef = Hello
  11. scala>val choice = someObj match {
  12.      | case _:java.io.File => "File"
  13.      | case _:String => "String"
  14.      | case _ => "Dunno"
  15.      | }
  16. choice: java.lang.String = String
  17. scala>val result = try {
  18.      | "two".toInt
  19.      | }catch{
  20.      | case e:NumberFormatException => -1
  21.      | case _ => 0
  22.      | }
  23. result: Int = -1
  24. scala>var i=0
  25. i: Int = 0
  26. // while and do-while do not have return values
  27. scala>while( i<4 ){
  28.      | "22"
  29.      | i += 2
  30.      | }
  31. scala> println( if(i>0) "great"else"less" )
  32. great
  33. // code blocks return the last statement
  34. scala>val m = {
  35.      | val x = 1
  36.      | x + 2
  37.      | }
  38. m: Int = 3