Exceptions Learn programming Java

Lesson:

Flow Control


Exercise:

Exceptions 45


Objetive:

Create a java program to ask the user for two numbers and display their division. Errors must be trapped using "try..catch".


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		int number1;
		int number2;
		int division;

		System.out.print("Enter a number to divide: ");
		number1 = Integer.parseInt(new Scanner(System.in).nextLine());

		System.out.print("Enter another number to divide: ");
		number2 = Integer.parseInt(new Scanner(System.in).nextLine());

		try
		{
			division = number1 / number2;

			System.out.printf("%1$s / %2$s = %3$s" + "\r\n", number1, number2, division);
		}

		catch (DivideByZeroException e)
		{
			System.out.println("Cannot divide by Zero");
			return;
		}
	}
}