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