Creating a personal exception class.
We're supposed to create a program for a class wherein it accepts an input for an age, then if the age is less than 0 throws an exception and stops the program. I cannot figure out how exception classes work for the life of me. Any help on where I'm going wrong? Thanks!
Code:
import java.util.Scanner;
public class A {
public static void checkAge(int age) throws Exception{
if(age < 0){
ageException b = new ageException("Invalid.");
}
}
public static void main(String[] args) throws Exception {
A a = new A();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = 0;
try{
age = keyboard.nextInt();
checkAge(age);
}
catch (ageException b) {
System.out.println(b.v);
}
System.out.println("Thanks. You say you are "+ age + " years old.");
}
}
Exception:
Code:
public class ageException extends Exception {
String v;
public ageException(){
}
ageException(String z){
String v = z;
}
public static void main(String[] args) {
}
}
Re: Creating a personal exception class.
Your overloaded constructor on line 8 is missing the the scope - it should also be public. In your checkAge method, you need to throw a new exception:
Code:
throw new ageException("My message here");
Also, this is just a style note (but an important one), your class names should never start with a lowercase letter - lowercase is reserved for methods, variables, and key words.