Write a program, to show the behavior of ‘try / catch block and finally’. In this, write a suitable
program to check the following scenario.
‘Allow the user to input two numbers. Divide the first number entered by the second number and
display the answer. In case, if the user enters the second number as ‘0’, program may generate a run
time exception.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int num1,num2;
System.out.println("Enter first number: ");
Scanner in=new Scanner(System.in);
num1=in.nextInt();
System.out.println("Enter second number: ");
num2=in.nextInt();
int result;
try{
result=num1/num2;
System.out.println(num1+" / "+num2+" = "+result);
}
catch(Exception e){
System.out.println(e);
}
}
}
Comments
Leave a comment