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.

  1. Identify the events / block of code that can cause exception and enclose it with try block.
  2. Write a logic Exception Handling logic if any, inside the catch block which can be written only associating to try block only.
  3. On any case if you have any resource used during the exception block(try), close it before you say exception handled use finally.
  4. Remember Exception event cannot be enclosed with try when there is no either catch or finally  associated with it.
  5. catch & finally are both not mandatory blocks but any one at-least associate with try immediately.

Advertisements