A try-catch block lets you attempt risky code and handle the exception if one occurs, instead of letting your program crash:
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Java runs the code inside try. If no exception occurs, the catch block is skipped entirely. If an exception of the specified type is thrown, Java jumps to the catch block immediately. Any remaining lines in try after the throwing line do not run.
The variable e holds the exception object. You can call e.getMessage() to get a description of what went wrong.