Object Oriented Programming: Unit III: Exception Handling and Multithreading

try-catch Block

with Example Exception Handling Java Programs

The statements that are likely to cause an exception are enclosed within a try block. For these statements the exception is thrown.

try-catch Block

• The statements that are likely to cause an exception are enclosed within a try block. For these statements the exception is thrown.

• There is another block defined by the keyword catch which is responsible for handling the exception thrown by the try block.

• As soon as exception occurs it is handled by the catch block.

• The catch block is added immediately after the try block.

•  Following is an example of try-catch block

try

{

//exception gets generated here

}

catch(Type_of_Exception e)

//exception is handled here

}

• If any one statement in the try block generates exception then remaining statements are skipped and the control is then transferred to the catch statement.

Java Program[RunErrDemo.java]

class RunErrDemo

{

public static void main(String[] args)

{

int a,b,c;

a=10;

b=0;

try

{

Exception occurs because the element is divided by 0.

{

c=a/b;

}

catch(ArithmeticException e)

{

System.out.println("\n Divide by zero");"

}

System.out.println("\n The value of a: "+a);

System.out.println("\n The value of b: "+b);

}

}

Output

Divide by zero

The value of a: 10

The value of b: 0

Note that even if the exception occurs at some point, the program does not stop at that point.

Object Oriented Programming: Unit III: Exception Handling and Multithreading : Tag: : with Example Exception Handling Java Programs - try-catch Block