Let’s
now look at an example where the running code generates multiple types of
exceptions. Rather than providing a generic exception handler to catch all types
of exceptions, we provide an exception handler for each type of exception that
may be generated by the running code. The application asks the user to enter a
valid URL, opens it in the program using the built-in URL class, and dumps its
contents (albeit in simple text format, for simplicity) to the user console.
Now, what kinds of errors can we envision in this simple application?
At the simplest level,
·
the user might not enter any
URL
·
the entered URL might be
invalid
·
the user might forget to
specify the protocol
·
there might be an error
opening the URL
· the data reading might generate I/O errors
There
could be any number of unforeseen errors. Our program will try to safeguard
against all these errors, and if an error occurs, it will take corrective
action to ensure against a program crash. Following program illustrates this
use of multiple exception handlers.
import java.io.*;
import java.net.*;
public class MultipleExceptionsExample {
public static void main(String[] args) {
String urlStr = null; while (true) {
try {
System.out.print("Enter url: ");
BufferedReader reader = new BufferedReader( new InputStreamReader(System.in));
urlStr = reader.readLine();
if (urlStr.length() == 0) {
System.out.println("No url specified:");
continue;
}
System.out.println("Opening " + urlStr);
URL url = new URL(urlStr);
reader = new BufferedReader(new InputStreamReader(
url.openStream()));
System.out.println(reader.readLine());
reader.close();
} catch (MalformedURLException e) {
System.out.println("Invalid URL " + urlStr + ": "
+ e.getMessage());
} catch (IOException e) {
System.out.println("Unable to execute " + urlStr + ": "
+ e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
Note
that the application uses certain classes from the java.io and java.net
packages. To understand the current application, we do not need a deep
understanding of these classes. We will focus mainly on what happens when the
execution of the code within these classes generates errors at runtime.
· The main method defines an
infinite loop to accept the user input endlessly. The user is asked to enter a
desired URL. The program reads the input using BufferReader.
· Then we read a line of input
from the keyboard (until the enter key is pressed) and assigns it to the urlStr
variable. The program then checks whether the user indeed input some string
· Next, we try to establish a
connection to this URL
· At this time, if the URL is invalid, it will generate an error. This is caught in the MalformedURLException exception handler.
The following output shows what happens when an invalid URL is entered:
Enter url: mindstick.com
Opening mindstick.com
Invalid URL mindstick.com: no protocol: mindstick.com
Enter url: ttp: // mindstick.com
Opening ttp: // mindstick.com
Invalid URL ttp: // mindstick.com: unknown protocol: ttp
Oops!
This time we missed the h in http. The same exception handler has trapped the
error, this time giving another message (unknown protocol), which again is an
appropriate one. Now, let’s enter the URL one more time without any mistakes.
The output is as follows:
Enter url: http://google.com
Opening http://google.com
<!doctype html><html><head><meta http-equiv="content-type" content="text/html;
charset=ISO-8859-1"><title>Google</title><script>window.google={kEI:"BK9TTbv
XJIjfcbD5sOEI",kEXPI:"28317,28600,28641,28722",kCSI:{e:"28317,28600,28641,28
722",ei:"BK9TTbvXJIjfcbD5sOEI",expi:"28317,28600,28641,28722"},ml:function()
{},kHL:"en",time:function(){return(new Date).getTime()},log:function(c,d,
catch (IOException e) {
System.out.println("Unable to execute " + urlStr + ": " + e.getMessage());
}
To understand this, try the following URL:
Enter
url: http://google.com:81
You will get the following output:
Opening http://google.com:81
Unable to execute http://google.com:81: Connection timed out: connect
This time the program executed the code in the IOException handler. Finally, why do we have the most generic exception handler at the end?
catch (Exception e) {
System.out.println(e.getMessage());
}
Jayden Bell
04-Apr-2017