Exceptions Learn programming Java

Lesson:

Flow Control


Exercise:

Exceptions


Objetive:

Create a java program to prompt the user for two numbers and display their division. Errors should be caught 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;
		}
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.