1: Custom exception class:
package Custom exception; // Or inherit RuntimeException (runtime exception) public class MyException extends Exception { private static final long serialVersionUID = 1L; // Provide a constructor without parameters public MyException() { } // Provide a constructor with parameters public MyException(String message) { super(message); // a Pass the parameter to Throwable's constructor with String parameters} }2: Write a method class for testing scores: This is to throw an exception class that you wrote yourself
package Custom exception; public class CheckScore { // Method to check the legitimacy of scores check() If the definition of runtime exceptions, there is no need to throw exceptions public void check(int score) throws MyException {// Throw your own exception class if (score > 120 || score < 0) { // Throw an exception when the score is illegal throw new MyException("The score is illegal, the score should be between 0--120");// new one's own exception class} else { System.out.println("The score is legal, your score is" + score); } } }Three: Write a test score. If there is an exception, catch it and don't throw it out.
package Custom exception; import java.util.Scanner; /* * Custom exception testing class*/ public class Student { public static void main(String[] args) { Scanner 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(); } } }The above is the entire content of the simple example of customizing an exception template brought to you by the editor. I hope everyone can support Wulin.com more~