Friday 7 July 2017

try() - catch() Block

There are 5 keyword used in Exception such as:-
1)    try
2)   catch
3)   finally
4)   throw
5)   throws

1)  try Block: 

Its used to place code that may throw exception. It must be used with catch or finally block.
syntax are given below.

A)   syntax:-  try and catch block:-

         try{
                   // code that may be exceptions occurs
             }
         catch(Exception_class name ref )
            {
                  //code
            }

B)  syntax:- try and finally

          try{
                 //code where may be exception occurs
             }
          finally(){}


Example:write a simple program without exception handling.

     public class A{   
       public static void main(String args[]){   
        int a=10/0;//may throw exception   
             System.out.println("some other code...");   
       }  }

output:- 

 Exception in thread "main" java.lang.ArithmeticException: / by zero
          at A.main(A.java:8)




 In example 1 occur exception and "some other code" statement of  the program are not printed here.
so lets write a program to solve the problem.



Example:- program to handle exception .

public class ExceptionExample {
public static void main(String[] args) {
    try{
        int a=10/0;
        }
    catch(Exception e)
    {
        System.out.println(e);}

System.out.println("some other code");
}}
output: 
java.lang.ArithmeticException: / by zero
some other code



Now in this program we used to try{}block and catch(){}block so printed the "some other code' statement in the program.



2)  catch block:- 

 It is used to handle exception. It must be used with try block.

  Syntax:-   

      try
           {    
                  //code where may be exception occure
            }
      catch(Exception_class_ref)
           {
                  //code
           }


Example:- 

import java.util.concurrent.ExecutionException;
public class ExceptionCatchBlock {
public static void main(String[] args) {
    try{
        String s1=null;
        System.out.println(s1.length());
        }

   catch(Exception e){System.out.println(e);}
    System.out.println("other code");
 }
 }

output:- 

java.lang.NullPointerException
other code


Example:- Write a program to use catch block with array. 

public class a2 {
public static void main(String[] args) {
    try{
        int[] a=new int[5];
         a[5]=20;
      System.out.println(a[5]);}
     catch(Exception  e){System.out.println(e);
           System.out.println("some other code");
    }}}
 

output:- 

java.lang.ArrayIndexOutOfBoundsException: 5
some other code






I will describe finally throw and throws  further.

No comments:

Post a Comment