September 2018
Intermediate to advanced
398 pages
9h 43m
English
A try...catch block can optionally be followed by a finally {} block. The code inside the finally block is always executed, even if an exception is not matched by any pattern in the catch block. The finally block is typically used to close any resource that is accessed inside the try block, such as a file or a network connection.
The following code shows how to use a URL to read a web page into a string:
import java.io.IOExceptionimport java.net.URLimport scala.annotation.tailrecval stream = new URL("https://www.packtpub.com/").openStream()val htmlPage: String = try { @tailrec def loop(builder: StringBuilder): String = { val i = stream.read() if (i != -1) loop(builder.append(i.toChar)) else builder.toString() } loop( ...
Read now
Unlock full access