Handling Errors/Exceptions in Java with try-catch-finally Construct:
To manage errors or exceptions during the execution of a code block, Java employs the try-catch-finally construct. The basic structure is as follows:
try {
// Code that may throw errors/exceptions
} catch (ExceptionType ex) {
// Code to handle the exception
} finally {
// Code always executed, regardless of whether an exception is thrown or not
// Perform cleanup or resource release here
}
For instance, consider the following code that catches an exception potentially thrown when parsing a number from an input string:
String input = "";
// Capture input from the user...
int number;
try {
number = Integer.parseInt(input);
} catch (NumberFormatException ex) {
number = -1; // Assign a default value
}
Key Rules about try-catch-finally Construct in Java:
try {
number = Integer.parseInt(input);
} finally {
number += 100;
}
The finally block is also optional, but its code is always executed, irrespective of whether an exception is thrown or not.
An exception is if there is a System.exit()
command executed in either the try or catch block. In such cases, the finally block won't be executed. For instance:
try {
number = Integer.parseInt(input);
} catch (NumberFormatException ex) {
number -= 100;
if (number < 0) {
System.exit(0);
}
} finally {
number += 100; // This block won't be executed if System.exit() is called
}
Java SE 1.7 Enhancement: Try-with-Resources Statement:
With the release of Java SE 1.7, an additional form of the try-catch statement is introduced, known as the try-with-resources statement.