Java Program to Divide Two Numbers and Catch the Exception, If Divisor Is 0

You are currently viewing Java Program to Divide Two Numbers and Catch the Exception, If Divisor Is 0

Java program to divide two numbers and catch the exception, if divisor is 0

package ExceptionHandling;

import java.util.Scanner;

class Ex1
{  
	public static void main(String arg[])
    {  
		try
		{
			// declare and initialize here.
			int a,b,c;
			Scanner KB=new Scanner(System.in);
			
			// input numbers here.
			System.out.print("Enter first number : ");
			a=KB.nextInt();
       
			System.out.print("Enter second number : ");
			b=KB.nextInt();
       
			//throw to catch
			c=a/b;
			System.out.println("Result:"+c);
		}
		catch(ArithmeticException e)
		{
			System.out.println("Error:"+e.getMessage());
			System.out.println("Error:"+e);
		}
		// here program ends.
		System.out.println("End of Program...");
	}
}

Output

First run:
Enter first number : 100
Enter second number : 0
Error:/ by zero
Error:java.lang.ArithmeticException: / by zero
End of Program...

Second run:
Enter first number : 70
Enter second number : 5
Result:14
End of Program...

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply