In: Computer Science
Please upvote if you are able to understand this and if there is any query do mention it in the comment section.
CODE:
class ExceptionThrown {
static int divideByZero(int a, int b) {//creating a static method
with int returntype
int i = a / b;
return i;
}
static int computeDivision(int a, int b) {//creating a static
method with int returntype
int res = 0;
try {//using try catch for exception handling
res = divideByZero(a, b);//calling the function divideByZero
} catch(NumberFormatException ex) {//using the class
NumberFormatException
System.out.println("NumberFormatException is occured");
}
return res;
}
public static void main(String args[]) {//main function
int a = 1;
int b = 0;
try {//using try catch for exception handling
int i = computeDivision(a, b);//calling the function
computeDivision
} catch(ArithmeticException ex) {//using the class
ArithmeticException
System.out.println(ex.getMessage());//using the getMessage method
of ArithmeticException class
}
}
}
A class is created ExceptionThrown which has two static methods name divideByZero in which the two arguments a and b are passed that performs a / b operation and return. The other static method computeDivision uses the try catch block for exception handling. In the computeDivision the method divideByZero is called with a and b as the parameters which were arguments for computeDivision method. If the two integers will not be integers then the exception will be catched using NumberFormatException class. Then in the main method there are two integer variables a = 1 and b = 0. Again try catch block is used. The computeDivision is called with parameters a and b. As when a / b will be performed on calling computeDivision and on calling computeDivision divideByZero will be called. So a / b which is 1 / 0 will be performed. This will raise an error which is handled in the catch block using the ArithmeticException class and it is printed with the getMessage() method.