Customizing an exception class template code instance

Source: Internet
Author: User

One: Custom Exception class:

Package custom exception;//or inherited RuntimeException (runtime Exception) public class MyException extends Exception {    private static final long Serialversionuid = 1L;    Provides parameterless construction method public    myexception () {    }    //provides a constructor with arguments public    myexception (String message) {        Super (message);//The construction method with string arguments to pass parameters to Throwable    }}

Two: Write a test score of the method class: This inside is thrown a self-written exception class

Package custom exception; public class Checkscore {//checking score legality check () If you define a run-time exception, you don't have to throw the exception. public void check (int score) throws Myexcep tion {//throws own exception class if (Score > | | Score < 0) {///score is not valid throw exception throw new MyException ("score is not valid, score should be between 0--120");//New One The exception class} else {System.out.println ("score is valid, your score is" + Score);}}}

Three: Write a test score, if there is an exception, to capture, do not throw a

Package custom exception; Import java.util.scanner;/* * Custom Exception Test class */public class Student {public static void main (string[] args) {Scan NER sc = new Scanner (system.in); int score = Sc.nextint (); Checkscore check = new Checkscore (); try {Check.check (score);} catch (MyException e) {//Use your own exception class to catch exception E.printstacktrace ();} }}



Customizing an exception class template code instance

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.