Example Program

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        

Is an ArithmeticException a checked exception?

Answer:

No.

Example Program

Here is an example program. Notice that methodA has two try/catch structures. It uses the static method parseInt() of class Integer to convert a string of characters into a primitive int. If the string can't be converted, parseInt() throws a NumberFormatException.

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 );     // Convert the string to an int.
                                             // May throw a NumberFormatException    
    }
    catch ( NumberFormatException badData )
    {
      System.out.println( "Bad Input Data!!" );
      return;   // this is necessary; without it control will continue with the next try.
    }

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

  }

  public static void main ( String[] a ) 
  { 
    Scanner scan = new Scanner( System.in );
    String  inData;
    
    System.out.print("Enter the divisor: ");
    inData = scan.next();  // Read a string from standard input
    methodA( inData );     // send the string to methodA
  }
}

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 exits normally.

Copy the program 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 message will be printed?