You can use a try-catch statement to handle an exception and provide a useful response when an operation fails.
In this example, you will try to convert text into an integer. If the text is not a valid integer, the program will display a message and continue running.
Source code
Save the following code as TryCatchExample.java:
public class TryCatchExample {
void main() {
String input = "twenty";
try {
int number = Integer.parseInt(input);
IO.println("Parsed number: " + number);
} catch (NumberFormatException exception) {
IO.println("Cannot convert \"" + input + "\" to an integer.");
IO.println("Please enter a whole number, such as 20.");
}
IO.println("The program continues.");
}
}
Explanation
The variable input contains the text to convert:
String input = "twenty";
The try block contains the operation that may throw an exception:
try {
int number = Integer.parseInt(input);
IO.println("Parsed number: " + number);
}
Integer.parseInt() converts a valid integer string, such as "20", into an int.
If the text cannot be parsed as an int, the method throws a NumberFormatException. This also happens when the number is outside the range supported by int.
Catching the exception
The catch block handles NumberFormatException:
catch (NumberFormatException exception) {
IO.println("Cannot convert \"" + input + "\" to an integer.");
IO.println("Please enter a whole number, such as 20.");
}
Since "twenty" is not a valid integer string, execution moves from Integer.parseInt() to this block.
The remaining statement inside the try block is skipped, so "Parsed number: ..." is not printed.
The parameter exception refers to the exception object. This example provides its own message rather than displaying the exception’s technical details.
Continuing after the catch block
After the exception is handled, execution continues with the statement following the try-catch:
IO.println("The program continues.");
Catching an exception does not retry the failed operation automatically.
Run the example
Compile and run the file:
javac TryCatchExample.java
java TryCatchExample
Output
Cannot convert "twenty" to an integer.
Please enter a whole number, such as 20.
The program continues.
If you change input to "20":
String input = "20";
The conversion succeeds, the catch block is skipped, and the output becomes:
Parsed number: 20
The program continues.
Catch the specific exception you can handle. Here, NumberFormatException clearly identifies the expected conversion failure.
