Object Oriented Programming: Unit III: Exception Handling and Multithreading

Using throws

with Example Exception Handling Java Programs

When a method wants to throw an exception then keyword throws is used. Let us understand this exception handling mechanism with the help of simple Java program.

Using throws

• When a method wants to throw an exception then keyword throws is used. The syntax is 

method_name(parameter_list) throws exception_list

{

}

• Let us understand this exception handling mechanism with the help of simple Java program.

Java Program

/* This programs shows the exception handling mechanism using throws

*/

class ExceptionThrows

{

static void fun(int a,int b) throws ArithmeticException

{

int c;

try

{

c=a/b;

}

catch(ArithmeticException e)

{

System.out.println("Caught exception: "+e);

}

}

public static void main(String args[])

{

int a=5;

fun(a,0);

}

}

Output

Caught exception: java.lang.ArithmeticException: /by zero

• In above program the method fun is for handling the exception divide by zero. This is an arithmetic exception hence we write

static void fun(int a,int b) throws ArithmeticException

• This method should be of static type. Also note as this method is responsible for handling the exception the try-catch block should be within fun.

Object Oriented Programming: Unit III: Exception Handling and Multithreading : Tag: : with Example Exception Handling Java Programs - Using throws