try/catch Statement
The try/catch statement encloses some code and is used to
handle errors and exceptions that might occur in that code. Here is
the general syntax of the try/catch statement:
The try/catch statement has four parts. The
body-code contains code that might throw the exception that we
want to handle. The exception-classname is the class name of
the exception we want to handle. The variable-name specifies a
name for a variable that will hold the exception object if the
exception occurs. Finally, the handler-code contains the code
to execute if the exception occurs. After the handler-code executes,
execution of the thread continues after the try/catch
statement. Here is an example of code that tries to create a file in
a non-existent directory which results in an IOException.
Here's the output:
It is possible to specify more than one exception handler in a
try/catch statement. When an exception occurs, each handler
is checked in order (i.e. top-down) and the handler that first matches
is executed. The following example registers a name at a website. The
example code can throw two kinds of exceptions one if the URL is
invalid and one if the web page is not accessible. This example uses
an invalid URL which results in a MalformedURLException.
Here's the output:
Here is the same example with a valid URL. The URL refers to a
non-existant web page which results in a IOException.
Here's the output:
When an exception occurs, the exception is compared with the specified
exception class name using the instanceof comparator. This means
that if the handler specifies a class name E, then any exception whose
class either equals E or is a subclass of E, matches the handler. The
following example catches either MalformedURLException or
IOException using Exception since both exceptions are
subclasses of Exception.
Here's the output:
If an exception occurs and does not match any of the handlers,
the exception is passed to any enclosing try/catch
statements and up the call chain until it is caught by some
handler. If the exception is not handled by any handler, it becomes an
uncaught exception and the thread is immediately terminated. In
the following example, a NullPointerException is thrown, which is
not caught by MalformedURLException and so becomes an
uncaught exception.
The result of an uncaught exception is a stack trace that identifies
the line of code that threw the exception. The output looks something
like:
try {
body-code
} catch (exception-classname variable-name) {
handler-code
}
String filename = "/nosuchdir/myfilename";
try {
// Create the file
new File(filename).createNewFile();
} catch (IOException e) {
// Print out the exception that occurred
System.out.println("Unable to create "+filename+": "+e.getMessage());
}
// Execution continues here after the IOException handler is executed
Unable to create /nosuchdir/myfilename: The system cannot find the path specified
// This URL string is deliberately missing the http: protocol to cause an exception
String urlStr = "xeo.com:90/register.jsp?name=joe";
try {
// Get the image
URL url = new URL(urlStr);
InputStream is = url.openStream();
is.close();
} catch (MalformedURLException e) {
// Print out the exception that occurred
System.out.println("Invalid URL "+urlStr+": "+e.getMessage());
} catch (IOException e) {
// Print out the exception that occurred
System.out.println("Unable to execute "+urlStr+": "+e.getMessage());
}
Invalid URL xeo.com:90/register.jsp?name=joe: no protocol: xeo.com:90/register.jsp?name=joe
urlStr = "http://xeo.com:90/register.jsp?name=joe";
try {
URL url = new URL(urlStr);
InputStream is = url.openStream();
is.close();
} catch (MalformedURLException e) {
// Print out the exception that occurred
System.out.println("Invalid URL "+urlStr+": "+e.getMessage());
} catch (IOException e) {
// Print out the exception that occurred
System.out.println("Unable to execute "+urlStr+": "+e.getMessage());
}
Unable to execute http://xeo.com:90/register.jsp?name=joe: Connection refused: connect
urlStr = "http://xeo.com:90/register.jsp?name=joe";
try {
URL url = new URL(urlStr);
InputStream is = url.openStream();
is.close();
} catch (Exception e) {
// Print out the exception that occurred
System.out.println(urlStr+": "+e.getMessage());
}
http://xeo.com:90/register.jsp?name=joe: Connection refused: connect
// This string is deliberately set to null to cause an exception
urlStr = null;
try {
int len = urlStr.length(); // Causes a NullPointerException
URL url = new URL(urlStr);
} catch (MalformedURLException e) {
// Print out the exception that occurred
System.out.println("Invalid URL "+urlStr+": "+e.getMessage());
}
Exception in thread "main" java.lang.NullPointerException
at MyClass.mymethod(MyClass.java:162)
stupid code
yeah its stupid
it's really not that bad, don't be babies
It's a perfectly simple & clear example of try-catch exception handling, "stupid code" is both an unqualified and rude comment from (I suspect) a "stupid" person.
juz wondering why is there the expected problem after i use the try-catch exception?Help any1?
nice one
only for the noobs
This code is FAR from being stupid. In fact the examples showed here are awesome and perfectly clear.
The issue is that stack variables, i.e. handleFileIn and dataFileIn, are not automatically initialized to null like instance variables. Java does this for efficiency reasons.
However, Java will never allow you to use an uninitialized variable. Your code has a particular path in which an uninitialized variable will get used. In particular, if new FileInputStream("test.txt") throws an exception, dataFileIn will be uninitialized in the call to dataFileIn.available(). The compiler detects this potential situation and then complains.
The typical way this kind of coding is done is to explicitly initialize handleFileIn and dataFileIn with null and then using them within the try clause. And then in the catch clause, close the input streams if the input streams are not null.