Possible Exceptions

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

The catch{} blocks are in a correct order, because ArithmeticException is not an ancestor nor a descendant of InputMismatchException. Reversing the order of the two blocks would also work.

Possible Exceptions

In the example program, the try{} block might throw a NumberFormatException, or an ArithmeticException.

  public static void main ( String[] a ) 
     . . . .

    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 )
    {
      . . .
    }

    catch (ArithmeticException ex )
    {
      . . .
    }
  }

A NumberFormatException might occur in either call to nextInt(). The first catch{} block is for this type of Exception.

An ArithmeticException might occur if the user enters data that can't be used in an integer division. The second a catch{} block is for this type of Exception.

QUESTION 13:

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