Java program to read two integers a and b. Compute a/b and print, when b is not zero. Raise an exception when b is equal to zero.

Program: Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero. Raise an exception when b is equal to zero.

Aim: Exception handling in java, introduction to the throwable class, throw, throws, and finally.

import java.util.*; 

public class TryP 
{ 
int c; 

void div(int a,int b) 
{ 
try 
{ 
c=a/b; 
System.out.println("Result="+c); 
} 
catch(ArithmeticException e) 
{ 
System.out.println("Cannot divide by zero"); 
} 
} 

public static void main(String args[]) 
{ 
TryP obj=new TryP(); 
Scanner in=new Scanner(System.in); 
System.out.println("Enter the values of a and b"); 
int no1=in.nextInt(); 
int no2=in.nextInt(); 
obj.div(no1,no2); 
} 
} 

Output:-

Leave a Reply

Your email address will not be published. Required fields are marked *