Java Try-Catch
The try statement allows you to define a block of code
to be tested for errors while it is being executed.
The catch
statement allows you to define the action to be taken if an error occurs in the
try block.
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Example
If an error occurs, we can use try...catch to "catch" the error and
execute some code to handle it instead of letting the program crash.
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // Error!
} catch (Exception e) {
System.out.println("Something went wrong.");
}
Without the try-catch block, the program would stop immediately and show a scary error message to the user.
Click Run to execute your code
Debugging
Inside the catch block, you usually want to print details about the error so you
can fix it. You can print the exception object e or call
e.printStackTrace().
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
Summary
- Put code that might throw an error inside
try { ... }. - Put code to handle the error inside
catch(Exception e) { ... }. - This prevents your application from crashing unexpectedly.
Enjoying these tutorials?