Throwing an Exception

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        

Answer:

main() calls MethodA
MethodA calls parseInt()
parseInt() throws a NumberFormatException.
MethodA catches the exception and prints "Bad Input Data!!"
The return statement executes.
Control returns to main().

Throwing an Exception

Your program can throw an exception when it detects a problem. The problem can be unique to your application. For example, say that a program for an insurance company calculates a person's age by subtracting their year of birth from the year 2000. Then it calculates the number of years they have been driving by subtracting 16 from their age. Someone who has been driving less than 4 years gets charged $1000 for insurance, otherwise they are charged $600. If a person's age is less than 16 they cannot get insurance, so an exception is thrown.

import java.util.* ;
import java.io.* ;

public class RateCalc
{

  public static int calcInsurance( int birthYear ) throws Exception
  {
    final int currentYear = 2000;
    int age = currentYear - birthYear;

    if ( age < 16 )
    {
      throw new Exception("Age is: " + age );
    }
    else
    {
      int drivenYears = age - 16;
      if ( drivenYears < 4 )
        return 1000;
      else
        return 600;
    }
  }

  public static void main ( String[] a ) 
  {
    Scanner scan = new Scanner( System.in ) );
    System.out.println("Enter birth year:");
    int inData = scan.nextInt();

    try
    {
      System.out.println( "Your insurance is: " + calcInsurance( inData ) );
    }
    catch ( Exception oops )
    {
      System.out.println( oops.getMessage() + " Too young for insurance!" );
    }

  }
}

When a bad value is detected, the calcInsurance() method constructs an Exception and throws it to its caller, main(). The Exception is caught in main() and appropriate action taken.

The calcInsurance() method must say throws Exception because Exception is checked.

QUESTION 10:

(Software Design Question: ) Do you think this is a well designed program?