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 Java
monitored 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 Throwable
or Exception
class, the proposed Exception
class.
The syntax structure is shown below:
class MyException extends Exception {
…
}
Generally, we will define such an exception:
class MyException extends Exception {
public MyException(String m) {
super(m);
}
}
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:
MyException: 字符串m中的内容
In the process, it throws an exception syntax is:
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