Customizing a simple instance of an exception class template _java

Source: Internet
Author: User

One: Custom exception classes:

Package custom exception; 
 
or Inherit RuntimeException (Run-time exception) public 
class MyException extends Exception { 
 
  private static final long Serialversionuid = 1L; 
 
  Provides constructor methods with no parameters public 
  myexception () { 
  } 
 
  //provides a parameterized constructor public 
  myexception (String message) { 
    Super (message);/A passes parameters to the Throwable constructor with string parameters 
   
 

Two: write a test score of the method class: This inside is thrown a write their own exception class

Package custom exception; 
 
public class Checkscore { 
 
  //Check score legality method check () If you define a Run-time exception, you do not have to throw an exception. Public 
  void Check (int score) throws myexception {///throws its own exception class 
    if (Score > | | | | Score < 0) { 
      //score is illegal when throwing an exception 
      throw new MyException ("score is not valid, cent Number should be between 0--120 ");/new one's own exception class 
    } else { 
      System.out.println (" The score is valid, your score is "+ score) 
    ; 
  } 
} 

Three: write a test score, if there are exceptions, to capture, do not throw out the

Package custom exception; 
 
Import Java.util.Scanner; 
 * * Custom Exception Test class/* 
 public 
class Student {public 
  static void Main (string[] args) { 
    Scanner sc = new Sca Nner (system.in); 
    int score = Sc.nextint (); 
 
    Checkscore check = new Checkscore (); 
    try { 
      Check.check (score); 
    } catch (MyException e) {//catch exception E.printstacktrace () with its own exception class 
      ; 
  } 
 

The above is a small series for everyone to customize an exception class template Simple example of all the content, I hope that we support cloud Habitat Community ~

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.