Custom exception Classes in Java

Source: Internet
Author: User

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

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.