Exception handling in scala

2010-02-16

Scala is on top of my list of programming languages worth learning. From time to time I compare Scala‘s syntax with Java and noticed that exception handling in Scala is much identical to the Java way, so it‘s easy for a Java developer to get familiar with.

Here is a short list of differences in exception handling between Java and Scala

Unlike Java, Scala has no checked exceptions

i.e. checked exceptions in java are java.io.IOException. You don‘t have to handle them explicitly in Scala.

Java:

public int read(InputStream in) throws IOException {
return in.read();
}

Scala:

def read(in: InputStream) = in.read

Use the throws annotation to declare checked exceptions if you want to call your Scala method from Java

@throws(classOf[java.io.IOException])
def read(in: InputStream): Int = in.read

Scala uses pattern matching for the catch clause

Java:

public void parse (InputStream in) throws IOException {
try {
int c = 0;
while( (c = in.read()) > -1) {
// do something useful.
}

} catch(IOException ex) {
log.error(ex.getMessage(), ex);

} catch(Throwable t) {
log.error("An unexpected error occurred", t);
} finally {
in.close();
}
}

Scala:

@throws(classOf[java.io.IOException])
def parse(in: InputStream) {
try {
var i: Int = 0
while ((c = in.read()) > -1) {
// do something useful
}
} catch {
case e:IOException => log.error(ex.getMessage(), e)
case e => log.error("An unexpected error occurred", e)
} finally {
in.close
}
}

That‘s it. Are there still other things to know about exeception handling in Scala?


me

Marco Rico Gomez is a passionate software developer located in Germany who likes to share his thoughts and experiences about software development and technologies with others.


blog comments powered by Disqus