Custom Exceptions:
Exam results must be between 0-100 obviously there is no corresponding exception in Java, we need to do an exception
Custom exceptions
Inherit from exception
Inherit from RuntimeException
Here is a code example:
Packagecn.itcast_08;/** Java is unlikely to be considered in all cases, so in real development we may need to define our own exceptions. * and our own arbitrary write a class, is not as an exception class, to think your class is an exception class, you must inherit from exception or RuntimeException * Two ways: * A: Inherit exception * B: Inherit RuntimeException*/ Public classMyExceptionextendsException {Public myexception () {} public myexception (String message) {//Custom exception here if we do not know how to use the constructor method to assign a value, we follow the parent class (class) source code to see what people are doing with it. Super (message); }}//Public class MyException extends RuntimeException {//// }
1 Packagecn.itcast_08;2 3 Public classTeacher {4 Public voidCheckintScore)throwsMyException {5 if(Score > | | Score < 0) {6 Throw NewMyException ("score must be between 0-100");7}Else {8System.out.println ("Score No Problem");9 }Ten } One A //inherit from RuntimeException for MyException - //Public void Check (int score) { - //if (Score > | | Score < 0) { the //throw new MyException (); - //} else { - //System.out.println ("Score No Problem"); - // } + // } -}
1 Packagecn.itcast_08;2 3 ImportJava.util.Scanner;4 5 /*6 * Custom Exception test class7 */8 Public classStudentdemo {9 Public Static voidMain (string[] args) {TenScanner sc =NewScanner (system.in); OneSystem.out.println ("Please enter student results:"); A intScore =sc.nextint (); - -Teacher T =NewTeacher (); the Try { - T.check (score); -}Catch(MyException e) { - e.printstacktrace (); + } - } +}
Android (Java) Study Note 84: Custom exception classes