Java
Handling errors
A practical reference with examples you can run.
Introduction
Failures are part of a program, not an unusual exception to learning. Catch a specific failure near the operation that can fail. Give useful feedback and preserve enough context to recover without silently hiding the problem.
Syntax & example
public class Main {
public static void main(String[] args) {
try {
Integer.parseInt("hello");
} catch (NumberFormatException error) {
System.out.println("Please enter a number.");
}
}
}Expected output
Please enter a number.
Common mistakes
- Using a variable before assigning a value to it.
- Mixing text and numbers without converting deliberately.
- Skipping an empty input or a boundary value when testing.
Practice
Change the invalid input into a valid number and compare the result.
Main.javaYour ideas, in code.
Loading your editor…
Run your code to see the output here.
Ready to buildUTF-89 lines