2019.9.23java Tips

Today's look a little abnormal, yes it is content educoder inside, but it is so good that it is so

Links: https://www.educoder.net/tasks/xiocqmvkegbn

Custom exception

In Java, in addition to the Javamonitored system abnormality (subscript bounds, divide by zero, etc.), the user can customize the exception.

Abnormal use the same user-defined try{} catch{}capture, but must themselves be thrown by the user throw new MyException.

An exception is a class, user-defined exceptions must inherit from Throwableor Exceptionclass, the proposed Exceptionclass.

The syntax structure is shown below:

  1. class MyException extends Exception {
  2. }

Generally, we will define such an exception:

  1. class MyException extends Exception {
  2. public MyException(String m) {
  3. super(m);
  4. }
  5. }

The method of the above-described configuration code MyException(String m)by super()calling the parent class constructor, the effect is the following output results:

  1. MyException: 字符串m中的内容

In the process, it throws an exception syntax is:

  1. throw new MyException(""); //""为字符串m中的内容,由用户自定义  

Then on a piece of code to deepen understanding

import java.util.Scanner;

class MyException extends Exception {
    public MyException(String m) {
        super(m);
    }
}
public class MyExceptionTest {
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(System.in);
            int num = scanner.nextInt();
            /********** Begin *********/
            if(num >= 0){
                System.out.print("The number you entered is: " + num);
            } else{
                throw new MyException("Number cannot be negative!");
            }


            /********** End *********/
        }
        catch(MyException e) {
            System.out.print(e);
        }
    }
}

 

Sample input:-60

Sample output:chapter8.step3.MyException: Number cannot be negative!

Sample input:60

Sample output:The number you entered is: 60

Guess you like

Origin www.cnblogs.com/WildSky/p/11567966.html