Finally and Throw
The finally
block executes regardless of whether an exception is thrown or not. The throw
keyword is used to manually throw an exception.
try {
checkAge(15);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("This will always execute.");
}
void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("You must be 18+.");
}
}
finally
is useful for cleanup operations like closing files or connections.