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:
try { body-code } catch (exception-classname variable-name) { handler-code }
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.
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
Here's the output:
Unable to create /nosuchdir/myfilename: The system cannot find the path specified
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.
// 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()); }
Here's the output:
Invalid URL xeo.com:90/register.jsp?name=joe: no protocol: xeo.com:90/register.jsp?name=joe
Here is the same example with a valid URL. The URL refers to a non-existant web page which results in a IOException.
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()); }
Here's the output:
Unable to execute http://xeo.com:90/register.jsp?name=joe: Connection refused: connect
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.
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()); }
Here's the output:
http://xeo.com:90/register.jsp?name=joe: Connection refused: connect

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.

// 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()); }
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:
Exception in thread "main" java.lang.NullPointerException at MyClass.mymethod(MyClass.java:162)

Comments

18 Jan 2010 - 11:22pm by Anonymous (not verified)

stupid code

18 Jan 2010 - 11:24pm by Anonymous (not verified)

yeah its stupid

20 Jan 2010 - 8:29am by Anonymous (not verified)

it's really not that bad, don't be babies

22 Jan 2010 - 5:02am by Aaron Kelly (not verified)

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.

26 Jan 2010 - 10:29am by Anonymous (not verified)

juz wondering why is there the expected problem after i use the try-catch exception?Help any1?

28 Jan 2010 - 5:54pm by Anonymous (not verified)

nice one

4 Feb 2010 - 9:55pm by Anonymous (not verified)

only for the noobs

7 Feb 2010 - 4:21pm by Cube (not verified)

This code is FAR from being stupid. In fact the examples showed here are awesome and perfectly clear.

10 Feb 2010 - 4:18am by Alex (not verified)
I have a large experience with C and Assembly, but I'm a clueless noob in Java. Started studying it less than a week ago. I wrote the following piece o code:
FileInputStream handleFileIn; DataInputStream dataFileIn; try { handleFileIn = new FileInputStream("test.txt"); dataFileIn = new DataInputStream(handleFileIn); } catch (Exception err) { System.err.println("FileIn error"); } while (dataFileIn.available()!=0) { System.out.println (dataFileIn.readLine()); } dataFileIn.close();
The compiler says that "my variables may not have been initialized". Should all the code that handle the file contents be written inside the try{} ? What if I need to make another try/catch to create an output file, should they be nested ? Thanks for your help.
10 Feb 2010 - 8:37am by patrick

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.

8 Mar 2010 - 8:54pm by Arnold (not verified)
import java.io.*; class ex2 { public static void main(String args[]) { try { FileInputStream in=new FileInputStream("test.txt"); } catch(Exception e) { System.out.println("File not found"); System.out.println(e.getMessage()); } }}
8 Mar 2010 - 8:55pm by chamil at allit (not verified)
import java.io.*; class ex2 { public static void main(String args[]) { try { FileInputStream in=new FileInputStream("test.txt"); } catch(Exception e) { System.out.println("File not found"); System.out.println(e.getMessage()); } }}

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.