try,catchandfinallyare three code blocks used together to handle runtime exceptions safely so your program does not crash unexpectedly.try(The risky code): You wrap code that might cause an exception inside this block. If an error occurs, execution stops immediately and jumps to thecatchblock.catch(The safety net): This block runs only if a specific exception occurs in thetryblock. It lets you log the error, show a user-friendly message, or recover smoothly.finally(The cleanup crew): This block always runs after thetryandcatchblocks finish whether an exception was thrown or not. Developers use it to release resources like closing open files or database connections.
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}Q65. What is finally?
The finally block generally executes whether an exception occurs or not. It is commonly used for cleanup.
Q66. Can we have multiple catch blocks?
Yes. We can handle different exception types using multiple catch blocks. More specific exceptions must appear before broader exceptions.
Q67. What is a custom exception?
An exception created by the programmer according to application requirements.
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}Q68. Difference between final, finally and finalize?
Keyword | Meaning |
|---|---|
final | Restricts reassignment, overriding or inheritance |
finally | Exception-handling cleanup block |
finalize() | Deprecated finalization mechanism; not reliable for resource cleanup |