...except when something goes wrong!

Scala inherited the concept of exceptions from Java. However the syntax is much clearer then its predecessor counterpart:

val url = new URL("http://www.strumentiresistenti.org/nonSuchFile.html")
try {
  ... something ...
} catch {
  case _: MalformedURLException => println("Where did you send me?")
  case ex: IOException => ex.printStackTrace()
}

This example is taken with some minor modifications from the wonderful book written by Cay S. Horstmann “Scala for the impatient”. This book is such a wonderful introduction to Scala that Martin Odersky (Scala creator) asked Horstmann to freely release the first chapters to speed up Scala’s adoption. I’m reading it and I really recommend it to everyone.

Now, back to exceptions, first of all pay attention to the way exceptions are trapped. The first one is managed without using the exception object in the code, so the exception is not saved in a named variable. The use of an underscore in Scala replaces sometimes the star used in other languages, and sometimes just means “I don’t care of this, throw it away”. The use of _ may seems strange, the first time you see it. I wasn’t very surprised since Perl, another language I’ve used extensively, uses $_ to mean “the current value” (of the iteration, of the input line, …). If you feel uncomfortable with _, just remember the way a field to be filled is represented in a paper form: ___________________________ . Like an underscore.

Now: how can I add a block of code that must be executed, no matter if the try block threw an exception or not? Such code can be added in the finally block:

val in = new URL("http://www.strumentiresistenti.org/nonSuchFile.html").openStream()
try {
  ... something ...
} catch {
  case _: MalformedURLException => println("Where did you send me?")
  case ex: IOException => ex.printStackTrace()
} finally {
  in.close()
}

I find the Scala way very clear, clean and concise.