Custom exception class

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.