Exception Catch-all

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        

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 specific Exception not caught in the preceeding blocks. Do this so the user sees a pleasant error message rather than a confusing stack trace. Here is 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 (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" );

Now ArithmeticExceptions are caught in the first block, and all other Exceptions in the other.

QUESTION 20:

Where will a RunTimeException be caught?