Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala try/catch not catching some exceptions

Unless the try/catch doesn't work the why I think it should work, I'd expect the following exception be caught. Instead it just throws NPE.

try {
  scala.io.Source.fromInputStream(null)
} catch {
  case e:Throwable => println("oh cr*p!")
}

In contrast, the following code does work.

try {
  1/0
} catch {
  case e:Throwable => println("oh cr*p")
}
like image 717
Julio Avatar asked Apr 26 '13 07:04

Julio


People also ask

Why does Scala have no checked exceptions?

The Scala designers decided against checked exceptions, recognizing that thorough compile-time checking isn't always a good thing. The first branch has type Double, the second has type Nothing. Therefore, the if/else expression also has type Double.

How do you catch exceptions in Scala?

It is best practice in Scala to handle exceptions using a try{...} catch{...} block, similar to how it is used in Java, except that the catch block uses pattern matching to identify and handle exceptions.

Is try catch blocking?

The try... catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.

Why you should not use try catch?

With a try catch, you can handle an exception that may include logging, retrying failing code, or gracefully terminating the application. Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead.


1 Answers

io.Source is lazy, thus does not evaluate its input, until it is needed. Therefore the exception is not thrown when it is initialized, but when it is used for the first time. This example shows that:

scala> class Foo(val x: io.Source)
defined class Foo

scala> new Foo(io.Source.fromInputStream(null))
res2: Foo = Foo@1c79f780

No exception here. But as soon, as you use it (in this case to print it to the console) it throws an exception:

scala> res2.x
java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:78)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:129)

And a little tip: don't catch throwables, because that will also catch things like StackOverflowError and OutOfMemoryError, which you don't want to be catched.

like image 140
drexin Avatar answered Oct 27 '22 00:10

drexin