Argument Exception is an existing class that derives from Exception; you use it
ID: 3625174 • Letter: A
Question
Argument Exception is an existing class that derives from Exception; you use it when one or more of a method's arguments do not fall within an expected range. Create a class named Car Insurance containing variables that can hold a driver's age and state of residence. Within the class, create a method that accepts the two input values and calculates a premium. The premium base price is $100 for residents of Illinois (IL) and $50 for residents of Wisconsin (WI). Additionally, each driver pays $3 times the value of 100 minus his or her age. If the driver is younger than 16, older than 80, or not a resident of Illinois or Wisconsin, throw an Argument Exception from the method. In the Main() method of the Car Insurance class, try code that prompts the user for each value. If the user does not enter a numeric value for age, catch a FormatException and display an error message. Call the method that calculates the premium and catch the potential Argument Exception object. Save the file as Carlnsurance.cs.Explanation / Answer
using System;
namespace ConsoleApplication5
{
class CarInsurence
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
String state_residence;
int age;
int premium;
//inputting residence
Console.WriteLine("Enter State Residence:");
state_residence=Console.ReadLine();
try
{
//inputting Age
Console.WriteLine("Enter Age:");
age=Convert.ToInt32(Console.ReadLine());
premium=calculatePremium(state_residence,age);
Console.WriteLine("Premium:$"+premium);
}
catch(FormatException fe)
{
Console.WriteLine(fe.Message+"Invalid age Value.");
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
Console.Read();
}
static int calculatePremium(string arg,int ag)
{
int premium;
if(arg.Equals("Illinois"))
premium=100+(3*ag);
else if(arg.Equals("Wisconsin"))
premium=50+(3*ag) ;
else
{
if(ag<16 && ag>80)
throw new ArgumentException("Invalid inputs", "ag");
premium=0;
}
return premium;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.