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

Answer:

Yes. This program shows how Exceptions work, but in general if a situation can be handled by simple logic avoid using Exceptions


Better Program

Here is a better-written version of the program that detects the zero with an if:

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

Exception handling could be totally avoided by inspecting the input with Scanner.hasNextInt() before using Scanner.nextInt(), but that would be awkward.


QUESTION 15:

Can a try block explicitly throw an Exception?


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