go to previous page   go to home page   go to next page        

What type of Exception is thrown if the user enters a 0 for the divisor?

Answer:

An ArithmeticException.

Example Output

Here is a part of the program:

    try
    { 
      System.out.print("Enter the numerator: ");
      num = scan.nextInt();
      System.out.print("Enter the divisor  : ");
      div = scan.nextInt();
      System.out.println( num + " / " + div + " is " + (num/div) + " rem " + (num%div) );
    } 
    catch (InputMismatchException ex )
    { 
      System.out.println("You entered bad data." );
      System.out.println("Run the program again." );
    }
    catch (ArithmeticException ex )
    { 
      System.out.println("You can't divide " + num + " by " + div);
    } 
  }

Here is some sample output:

C:>java  DivisionPractice
Enter the numerator: Rats
You entered bad data.
Run the program again.

C:>java  DivisionPractice
Enter the numerator: 12
Enter the divisor: 6
12 / 6 is 2 rem 0

C:>java  DivisionPractice
Enter the numerator: 12
Enter the divisor: 0
You can't divide 12 by 0

QUESTION 14:

If a NoSuchElementExeption occurs in the try{} block, what happens? (You may wish to review how try/catch blocks work.)