Custom exception class
/** Custom throw Exception * custom Exception class: must inherit the classes of Error and Exception under Throwable. */Import java. util. extends; public class TestPersonException {public static void main (String [] args) {Person p = new Person (); sums in = new sums (System. in); // capture exceptions that may be thrown. try {System. out. print ("Enter age:"); p. setAge (in. nextInt (); System. out. println ("correct age:" + p. getAge (); System. out. print ("Enter Gender:"); p. setSex (in. next (); System. out. println ("correct gender:" + p. getSex ();} catch (AgeException | SexExc Eption e) {}}/ *** custom exception methods for the Person class setAge () and setSex (); ** @ author vitelon **/class Person {int Age; string Sex; // The setAge (int age) method may throw the AgeException custom exception public void setAge (int age) throws AgeException {if (age <1 | age> 120) {throw new AgeException (age); // throw AgeException custom exception} else {this. age = age ;}} public String getSex () {return this. sex;} public int getAge () {return this. age;} // The setSex (String sex) method declared may throw a SexException custom exception public void setSex (String sex) throws SexException {if (! (Sex. equals ("male") | sex. equals ("female") {throw new SexException (sex); // throw a custom SexException} else {this. sex = sex ;}}/ *** create a custom Exception class SexException inherits Exception ** @ author vitelon **/class SexException extends Exception {String Sex; public SexException (String sex) {// custom exception class constructor System. out. println ("Gender:" + sex + ", unreasonable! ") ;}}/*** Create custom Exception class AgeException inheritance Exception ** @ author vitelon **/class AgeException extends Exception {int Age; public AgeException (int age) {// custom exception class constructor System. out. println ("age:" + age + ", unreasonable! ");}}
Keep working on java. Review the abnormal code at the beginning.