Question
Java Exception Class problem: I am trying to create my own exception class and have an error thrown when a user puts a social security
Java Exception Class problem: I am trying to create my own exception class and have an error thrown when a user puts a social security number with the wron format but I am getting a build fail error that says:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception InvalidCustomerException; must be caught or declared to be thrown
at Main.main(Main.java:14)
My code:
public class Main { public static void main(String[] args) { Customer cust = new Customer("Alin", "Parker", "12333-45-6789"); System.out.println(cust); } }
____________________________________________________________
public class Customer { protected String firstName; protected String lastName; protected String socialSecurity; Customer(String firstName, String lastName, String socialSecurity) throws InvalidCustomerException { this.firstName = firstName; this.lastName = lastName; if(!socialSecurity.matches("\\d{3}-\\d{2}-\\d{4}")) { InvalidCustomerException f = new InvalidCustomerException(); throw f; } this.socialSecurity = socialSecurity; } @Override public String toString() { return "customer is " + firstName + lastName + socialSecurity ; } }
______________________________________________________________________
public class InvalidCustomerException extends Exception{ String socialSecurity; InvalidCustomerException() { super(); this.socialSecurity = socialSecurity; } @Override public String getMessage() { return "social security number: " + socialSecurity + " is invalid"; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started