Yes.
import java.util.* ; import java.io.* ; class TooYoungException extends Exception { TooYoungException ( int age ) { super( "Too Young for Insurance! Age is: " + age ); } } public class RateCalcTwo { public static int calcInsurance( int birthYear ) throws TooYoungException { final int currentYear = 2020; // hard-coded current year. Awkward. int age = currentYear - birthYear; if ( age < 16 ) { throw new TooYoungException( age ); } else { int drivenYears = age - 16; if ( drivenYears < 4 ) return 1000; else return 600; } } public static void main ( String[] args ) { Scanner scan = new Scanner( System.in ); try { System.out.println("Enter birth year:"); int inData = scan.nextInt(); System.out.println( "Your insurance is: " + calcInsurance( inData ) ); } catch ( TooYoungException oops ) { System.out.println( oops.getMessage() ); } catch ( Exception oops ) { System.out.println( oops.getMessage() ); } } }
The calcInsurance()
method throws a custom-built TooYoungException
when the age is below 16.
It might also throw an IOException
.
The main()
method catches TooYoungException
s and general Exceptions
(which will probably be IOExceptions
.)
This program has a hard-coded current year of 2020. There are ways to get the current year, but they are complicated. Here are some runs of the program (it would be good if you ran it a few times yourself):
C:\JavaSource> java RateCalcTwo Enter birth year: 1990 Your insurance is: 600 C:\JavaSource> java RateCalcTwo Enter birth year: 2012 Too Young for Insurance! Age is: 8
Have you just thrown a BoredSillyException
?