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