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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
try { //exception monitoring section. //This block is exception prone. //Checked or unchecked exception can be occurred here. } catch(Exception1 e) { // if exception occurred at try block and this catch is been triggered //then do some corrective operation } catch(Exception2 e) { // if exception occurred at try block and this catch is been triggered //then do some corrective operation } catch(Exception3 e) { // if exception occurred at try block and this catch is been triggered //then do some corrective operation } finally{ // once all try..catch block has been complete then what is expected to //happened at the last……those kind of things will be at this block. //for example: while doing file related operations and that has been //encountered in try catch block then resources(like file, stream etc) has to be //close/flushed/cleared. //clean up activity takes place } |
If you like the post then please socialize it. Happy Sharing. Loudly Subscribing.