What is Exception Handling in Java?: try, catch, throw, finally
Exception handling in Java is a mechanism to handle runtime errors so that the normal flow of the program can continue instead of crashing abruptly.
Key Keywords
try— wraps the code that might throw an exceptioncatch— handles the exception thrown by the try blockthrow— used to explicitly throw an exceptionthrows— declares that a method might throw an exceptionfinally— a block that always executes, whether an exception occurred or not
Basic Example
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("This block always runs");
}
Throwing a Custom Exception
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above");
}
}
Types of Exceptions
- Checked Exceptions — checked at compile time, such as
IOException - Unchecked Exceptions — occur at runtime, such as
NullPointerExceptionandArithmeticException - Errors — serious problems like
OutOfMemoryErrorthat applications usually shouldn't try to catch
You can use multiple
catch blocks after a single try to handle different exception types differently, and Java also supports a multi-catch syntax using the pipe (|) operator.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.