To handle error/exceptions which may occur during execution of a particular code, Java introduces try-catch-finally construct. The structure of this construct is as follows:

try {
    // code that may throws errors/excpetions
} catch (exception object is being thrown) {
    // code to handle exception
} finally {
    // code always executed, regardless of exception thrown or not,
    // i.e clean up resources
} 
For example, the following code catch an exception may be thrown when parsing a number from an input string:

String input = "";
// capture input from user...

int number;
try {
    number = Integer.parseInt(input);
} catch (NumberFormatException ex) {
    number = -1;    // assigns  a default value
}
 

Some Rules about try-catch-finally construct in Java:

The catch block can be optional. The following example show only a try-finally construct:

try {
    number = Integer.parseInt(input);
} finally {
    number += 100;
}
The finally block is also optional, as shown in the first example. But remember that code in finally block is always executed, regardless of whether the try block throwing exception or not. 

One exception for finally block is, if there is a System.exit() command executed either in the try or catch block, the finally block won't be executed. For example, in the following code, the finally block won't be executed if there is an exception thrown and the number is negative:

try {
    number = Integer.parseInt(input);
} catch (NumberFormatException ex) {
    number -= 100;
    if (number < 0) {
        System.exit(0);
    }
} finally {
    number += 100;
}
With the release of Java SE 1.7, the try-catch statement has an additional form called try-with-resources statement. 

 

Related Topics:

 



 

 

Other Recommended Tutorials:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment