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")
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With