Throw/throws Distinction and use

Source: Internet
Author: User

Throws E1,e2,e3 just tells the program that this method might throw these exceptions, and the caller of the method might want to handle the exceptions. And these abnormal e1,e2,e3 may be produced by the function body.

And the throw is clear where this exception is to be thrown.

void DoA () throws Exception1, Exception3 {   try {     ...   } catch (Exception1 e) {     throw e;   } catch (exceptio N2 e) {     System.out.println ("error");   }   if (A! = b)     throw new Exception3 ("Custom Exception");

  

Code block ... may produce abnormal Exception1, Exception2, and Exception3.
If a Exception1 exception is generated, it is captured and then thrown by the caller of the method to do the processing;
If the Exception2 exception is generated, the method does its own processing (printing out the wrong name), so the method does not throw out the Exception2 exception, void DoA () throws Exception1, Excpetion3 inside of the Exception2 also do not have to write;
The Exception3 exception is an error in the logic of the method, the programmer has to handle the logic error in the case of throwing an exception Exception3, the caller also needs to handle.

  • If the method body throws exception is not processed, the method head must be declared throws this exception
  • If the method body does not have a specific throws Exception, the method header declaration throws this Exception can have without adding

Throw/throws Distinction and use

Related Article

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.