Question #259588

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.’ 


Expert's answer

Source code

import java.util.Scanner;
public class Main
{
	public static void main(String[] args) {
		int n1,n2;
		System.out.println("Enter first number: ");
		Scanner in=new Scanner(System.in);
		n1=in.nextInt();
		System.out.println("Enter second number: ");
		n2=in.nextInt();
		
		int div;
		try{
		    div=n1/n2;
		    System.out.println(n1+" / "+n2+" = "+div);
		}
		catch(Exception e){
		    System.out.println(e);
		}
	}
}

Sample run 1



Sample run 2





LATEST TUTORIALS
APPROVED BY CLIENTS