Java 19-10 Implementation and testing of custom exceptions

Source: Internet
Author: User

1 /*2 * Java cannot be considered for all exceptions, so in real development we may need to define our own exceptions. 3 * and our own arbitrary write a class, is not as an exception class, to think of your class is an exception class, you must inherit from exception or RuntimeException4  * 5 * Two types of methods:6 * A: Inherited exception compile-time exception7 * B: Inherited runtimeexception Run-time exception8  */9  Public classMyExceptionextendsException {Ten     //non-parametric construction One      Publicmyexception () { A     } -     //with parametric construction -      Publicmyexception (String message) { the         Super(message);//call the method of the parent class throwable so that the specific cause of the exception can be indicated when an exception occurs -     } - } -  + //Public class MyException extends RuntimeException { - // + // }

1  Public classTeacher {2      Public voidCheckintScore)throwsMyException {3         if(Score > | | Score < 0) {4             Throw NewMyException ("score must be between 0-100");5}Else {6System.out.println ("Score No Problem");7         }    8}

Test class:

1 ImportJava.util.Scanner;2 3 /*4 * Custom Exception test class5  */6  Public classStudentdemo {7      Public Static voidMain (string[] args) {8Scanner sc =NewScanner (system.in);9System.out.println ("Please enter student results:");Ten         intScore =sc.nextint (); One  ATeacher T =NewTeacher (); -         Try { - T.check (score); the}Catch(MyException e) { - e.printstacktrace (); -         } -     } +}

Java 19-10 Implementation and testing of custom exceptions

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.