Hello, everyone, today to share with you how to customize the exception in Java, if there is a new experience, then add, welcome to the guidance of predecessors ...
First, on the API, look at the parent class for exceptions and errors:
Then, now suppose I have a loop (i=0;i<100;i++), I want to stop running when i==10, and execute my custom exception, what to do, see:
Custom Exception classes:
Custom exception classes, which need to inherit throwable or exception, and override the Printstacktrace () method, which is the result of a custom exception's execution
public class MyException extends throwable{
@Override
public void Printstacktrace () {
System.out.println ("My exception is");
}
}
Test class
public class exceptiontest{
public static void Main (String args[]) {
for (int i=0;i<100;i++) {
if (i==10) {
try{
throw new MyException ();//Execute my Custom exception (here throw is not throw exception, is execution exception, (note and throws difference: throws position is behind method, throw exception))
}catch (MyException e) {
E.printstacktrace ();//The custom class here inherits the Throwable class, and overrides the Printstacktrace () method, E is a subclass, there is no polymorphic relationship, so the method in the subclass is executed.
}
}
}
}
}
Custom exception Classes in Java