Java--Exception capture and processing--throws and throw keyword

Source: Internet
Author: User

7.2 Throws and throw keyword

7.2.1 Throws Keywords

You can use the throws keyword declaration when defining a method, using the method declared by throws to identify that the method does not handle the exception, and that it is handled at the call of the method.

Example: using the throws keyword

Example: Handling Exceptions

Tips:

The throws keyword can also be used in the main method, but the main method is the starting point of the program, so when the main method throws an exception upwards, the exception can only be thrown to the JVM for processing. The main method is the starting point for everything, and if you use throws in the Main method, then the problem is definitely left to the JVM for processing, which will cause the program to break and it is not recommended to use throws on the main method.

7.2.2 Throw keyword

Unlike the throws keyword, you can use the Throw keyword to artificially throw an exception, throwing an instantiated object that throws the exception class directly.

Example: Throwing an exception

 Package Limethrowable._7_2_2.throw_;  Public class ThrowDemo01 {    publicstaticvoid  main (string[] args) {          Try{            thrownew Exception ("Lime throw a Exception");         Catch (Exception e) {            e.printstacktrace ();     }}}

Console:

Throw a exception at    Limethrowable._7_2_2.throw_. Throwdemo01.main (Throwdemo01.java:7)

La La la

7.2.3 Example--application of throw and throws

Java--Exception capture and processing--throws and throw keyword

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.