Is an ArithmeticException a checked exception?

A good answer might be:

No.


Example Program

Here is an example program. Notice that methodA has two try/catch structures. (It could have been written with just one.)

import java.lang.* ;
import java.io.* ;

public class BuckPasser
{
  public static int methodB( int divisor )  throws ArithmeticException
  {
    int result = 12 / divisor;  // may throw an ArithmeticException
    return result;
  }

  public static void methodA( String input )
  {
    int value = 0;

    try
    {
      value = Integer.parseInt( input );    // may throw a NumberFormatException    
    }
    catch ( NumberFormatException badData )
    {
      System.out.println( "Bad Input Data!!" );
      badData.printStackTrace();
      return;   // this is necessary so the next try does not get control.
    }

    try
    {
      System.out.println( "Result is: " + methodB( value ) );
    }
    catch ( ArithmeticException zeroDiv )
    {
      System.out.println( "Division by zero!!" );
      zeroDiv.printStackTrace();
    }

  }

  public static void main ( String[] a ) throws IOException
  {
    BufferedReader stdin = 
        new BufferedReader ( new InputStreamReader( System.in ) );
 
    String  inData = null;
    System.out.println("Enter the divisor:");
    inData = stdin.readLine();

    methodA( inData );

  }
}

The clause "throws ArithmeticException" in the header of methodB() is not required, because ArithmeticExceptions are not checked. If the user enters a string "0" then

main() calls MethodA
MethodA calls MethodB
MethodB causes an ArithmeticException by dividing by zero

MethodB throws the exception back to MethodA
MethodA catches the exception and prints "Division by zero!!"
Control returns to main() (which does nothing.)

Copy the program to notepad, save it to a file, compile and run it. Play with it a bit. Exception handling is tricky; a little practice now will help you later.

QUESTION 9:

Now say that the user enters the string "Rats". What happens now?

main() calls MethodA
___________________________________
___________________________________
___________________________________
___________________________________
Control returns to main().