Continuing with the previous discussion , How to Handle Exception in Java In this topic, lets elaborate the discussion on handling exception in Java.
Java provides try – catch block to handle exception in Java,
1. try block includes exceptional events or scenarios.
2. catch block includes exception handlers.
3. Java introduces one more block finally, which is preferred mostly for closing allocated resources.
Java Exception handling will be done efficiently with try-catch-finally its three sequentially associated blocks.
try-catch-finally workflow, as described blocks can be defined based on the preference of the code. While handling exception we need to keep following points.
- Identify the events / block of code that can cause exception and enclose it with try block.
- Write a logic Exception Handling logic if any, inside the catch block which can be written only associating to try block only.
- On any case if you have any resource used during the exception block(try), close it before you say exception handled use finally.
- Remember Exception event cannot be enclosed with try when there is no either catch or finally associated with it.
- catch & finally are both not mandatory blocks but any one at-least associate with try immediately.