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


Object Oriented Programming: Unit III: Exception Handling and Multithreading



Under Subject


Object Oriented Programming

CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation



Related Subjects


Discrete Mathematics

MA3354 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation


Digital Principles and Computer Organization

CS3351 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation


Foundation of Data Science

CS3352 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation


Data Structure

CS3301 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation


Object Oriented Programming

CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation