Handle or Declare The Exception: try, catch, throw, throws, finally clauses

Exception handling works by transferring the execution of the program to an appropriate exception handler.
For example, if you try to open a file to do some operation then situation aises like,
  • File doesnot exist
  • Some network problem
  • No permission to open or read or write the file etc.
So its job of Exception Handler to do some action in case of exception occurs, if it’s handled.
Handle the Exception
There are some clauses which is used for exception handling like
  • try
  • catch
  • finally
  • throw
  • throws

Handle the exception

try {….} catch {…} finally {…}

Declare the exception

throws is used to pass back to calling method.

try

This is to monitor the exception.

catch

If exception occurred then exception handler will find best corresponding catch block.

finally

At the last finally block will be executed.

throw:

If some exception has been caught in catch block then developer can re-throw it.

throws:

Declare the exception. If developer doesn’t want to handle the exception then he/she can pass it back to calling method. Please read “ducking” the exception.
Note: There is no difference in handling or declaration of checked or unchecked exception.

Template of try catch Block


 

If you like the post then please socialize it. Happy Sharing. Loudly Subscribing.

Leave a Reply

Your email address will not be published. Required fields are marked *