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

Why can't the "Statements following the structure" be used to close a file that the method has opened?

Answer:

These statements will not execute if the try block throws an unhandled Exception.


Exception Catch-all

If the last catch block catches Exception, then it will catch any type of Exception not caught in the preceeding blocks. Do this so the user sees a pleasant error message rather than a confusing stack trace. In the following excerpt, ArithmeticExceptions are caught in the first block, and all other Exceptions in the 2nd block.

    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 (ArithmeticException ex )
    { 
      System.out.println("You can't divide " + num + " by " + div);
    } 
    catch (Exception ex )
    { 
      System.out.println("Something went wrong." );
    }
   
    System.out.println("Good-by" );

QUESTION 23:

Where will a RunTimeException be caught?


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