JAVA throws and declares exceptions

Source: Internet
Author: User
Tags java throws

In the process of programming, we often encounter this situation, in the current environment can not be resolved, such as user-passed parameter errors, IO device problems. At this point, the exception to be thrown from the current environment is submitted to the superior for processing.

In the Java language, use the throw keyword to throw an exception. Look at the following code

     Public classa**Exception {PrivateString ID;  Public voidSetID (String id) {if(id.length () = =7)                                {                                         This. ID =ID; }Else                              {                                        Throw NewIllegalArgumentException ("parameter length is not 7 bits"); }                    }       }  

Above the code, we throw an exception of type illegalargumentexception.

declaring exceptions

If an exception is thrown in a method body, we want the caller to be able to catch the exception. So, how do you tell the caller?

In the Java language, the throws keyword declares an exception that a method might throw, and in the above code we throw a illegalargumentexception type of

Abnormal. You can let the caller know what kind of exception the method is likely to have and catch it in time by doing the following:

     Public classa**Exception {PrivateString ID; //use the throws keyword to declare possible exceptions to this method           Public voidSetID (String id) throws Illegalexception {if(id.length () = =7)                                  {                                         This. ID =ID; }                                Else                               {                                         Throw NewIllegalArgumentException ("The parameter length should be 7"); }                      }       }  

JAVA throws and declares exceptions

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.