

import java.lang.ArithmeticException;
import java.util.InputMismatchException;
import java.util.Scanner;



public class DivideByZeroExceptionsDemo
{
	
	public class DivideByZeroException
    	extends ArithmeticException 
    {

		String message;

		public DivideByZeroException( String message )
		{
			this.message = message;
		}

		public String toString()
		{
			return( message );
		}
	}
	
	public static void main(String[] args)
	{
		DivideByZeroExceptionsDemo demo = new DivideByZeroExceptionsDemo();
		demo.go();
	}


	// go() implements the program's user interface, which  askas
	// the user to input a numerator and then a denomentaor.
	// The program computes the quotient of the two numbers.
	// The try block can generate two kinds of exceptions. The first
	// is an InputMismatchException which is thrown if the user does not
	// input an integer as expected. This exception is thrown by the 
	// readInt() method of Scanner.
	// The other exception that could br thrown is thrown by our own method
	// quotient which creates and throws a DivideByZeroException if the
	// method is passed a denomentaor of zero. 
	// The catch blocks catch the different kinds of exceptions and responds
	// accordingly.
	
	public void go()
	{
		Scanner s = new Scanner(System.in);

		int numerator, denomenator, result;

		try
			{
				// nextInt() will throw an InputMismatchException if the user does
				// not input an integer. Note that we are not required to catch this
				// exception because it is a subclass of RunTimeException but we have
				// decided to catch it here since we want to respond in that situation.
				System.out.println("Input the numerator:");
				numerator = s.nextInt();


				System.out.println("Input the denomenator:");
				denomenator = s.nextInt();
				
				result = quotient( numerator, denomenator );
				System.out.println( "The results is " + result );
			}
			// this block is entered if an InputMismatchException is thrown
			catch ( InputMismatchException ime )
			{
				System.out.println("You must enter an integer");
			}
			// this block is entered if an DivideByZeroException is thrown
			catch ( DivideByZeroException dbze )
			{
				System.out.println( dbze.toString() );
			}

	}


   // Definition of method quotient. Used to demonstrate
   // throwing an exception when a divide-by-zero error
   // is encountered.
   public int quotient( int numerator, int denominator )
      throws DivideByZeroException
   {
	  // the DivideByZeroException must be first instantiated and then thrown.
      if ( denominator == 0 )
         throw new DivideByZeroException("You can't divide by zero.");

      return ( numerator / denominator );
   }


}



