ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

Exception Handling in Java

An exception is any sort of deviation from what we a program is expecting. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions needs to be handled.

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.

  1. import java.io.*;
  2. public class ExceptionDemo{
  3.  
  4. public static void main(String args[]){
  5. try{
  6. int a[] = new int[2];
  7. System.out.println("Access element three :" + a[3]);
  8. System.out.println("Exception thrown :" + e);
  9. }
  10. System.out.println("Out of the block");
  11. }
  12. }

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

  1. try
  2. {
  3. //Protected code
  4. }catch(ExceptionType1 e1)
  5. {
  6. //Catch block
  7. }catch(ExceptionType2 e2)
  8. {
  9. //Catch block
  10. }catch(ExceptionType3 e3)
  11. {
  12. //Catch block
  13. }

The finally block

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

  1. try
  2. {
  3. //Protected code
  4. }catch(ExceptionType1 e1)
  5. {
  6. //Catch block
  7. }catch(ExceptionType2 e2)
  8. {
  9. //Catch block
  10. }catch(ExceptionType3 e3)
  11. {
  12. //Catch block
  13. }finally
  14. {
  15. //The finally block always executes.
  16. }
Facebook Comments

Check Your Domain Ranking

Leave a Reply

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

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!