Exceptions and resource handling
An exception carries failure information from the operation that failed to code that can handle it.
How it works
In the example, parsing happens inside the try block. The parser reaches x and throws before println can print a number. The matching catch then prints the guidance. Let unrelated failures reach a handler that actually knows what to do with them.
Walk through an example
Catch NumberFormatException if a user types letters where your program expects an integer. With try-with-resources, eligible resources such as files are closed at the end of the block.
What to watch for
Avoid catching all exceptions around a large method. Keep the guarded operation small so the catch block explains a known failure.
Code example
public class Main {
public static void main(String[] args) {
try {
System.out.println(Integer.parseInt("4x"));
} catch (NumberFormatException error) {
System.out.println("Enter a whole number.");
}
}
}Check your understanding
Why does the conversion fail?
See the example and explanation
- Worked example
- Given
Integer.parseInt("4x") - Answer
4x is not a complete integer.
The final x does not represent a digit, so the parser cannot turn the entire string into an integer.