What's going on with the Java Java Builder?

Source: Internet
Author: User

Tag: The constructor is checked for exception capture


The code is as follows:

public class Example040 {private Example040 E40 = new Example040 ();p ublic Example040 () throws Exception {throw new Excepti On ("Here is exception, not error");} public void output () {System.out.println ("A new Class");} public static void Main (string[] args) throws Exception {Example040 example040 = new Example040 (); Example040.output ();}}


Code Analysis:

Run the above code and throw a Stackoverflowerror exception. Like most programs that throw Stackoverflowerror exceptions, this program also contains an infinite recursion. When you invoke a constructor, the initialization of the instance variable runs before the constructor's body. in the above code, the initialization of the E40 variable invokes the constructor recursively, and the constructor initializes the variable's own E40 domain by invoking the constructor again, so that the recursion goes on indefinitely. These recursive calls throw a Stackoverflowerror exception before the constructor program body obtains an execution opportunity, because Stackoverflowerror is a subtype of Error and not a subtype of Exception, so a catch clause cannot capture it. When you add a static modifier to E40, the stack overflow exception disappears.

Make the following modifications to the above code, add two new variables, the new variable initialization will produce an exception:

public class example040 {// private example040  e40 = new example040 ();p rivate static example040 e40 = new  Example040 ();p rivate static class internal = e40.new internalclazz (). GetClass (); private internalclazz clazz =  (Internalclazz)  internal.newinstance ();p ublic  Example040 ()  /* throws exception */{// throw new exception ("Here is Exception, Not error ");} Public void output ()  {system.out.println ("A new class");} Class internalclazz {public internalclazz ()  {}}public static void main ( String[] args)  throws Exception {Example040 example040 = new  Example040 (); Example040.output ();}} 

The above program will not compile correctly because the constructor must declare all of the checked exceptions thrown by its instance initialization operation. Although its constructor does not have any program body, it throws two checked exceptions, instantiationexception and illegalaccessexception. They are class.newinstance thrown, and this method is called when the Clazz domain is initialized.

An improved approach to the above procedure is to create a private, static helper method that calculates the initial value of the domain and handles the exception appropriately, as follows:

Private Internalclazz Clazz = Newclazz ();p rivate static Internalclazz Newclazz () {try {return (Internalclazz) internal.ne Winstance ();} catch (Instantiationexception | Illegalaccessexception e) {e.printstacktrace ();} return null;}

In summary, the instance initialization operation is run prior to the constructor's program body. Any exception thrown by the instance initialization operation is propagated to the constructor. If the initialization operation throws a check exception, the constructor must declare that the exception is thrown, but this should be avoided because it can cause confusion. Finally, for the class we are designing, if its instance contains other instances of the same class, be careful with this infinite recursion.


note: This "Java Confusion" series are bloggers reading "Java doubts" The original book after the interpretation of the original book and examples of the adaptation and then write a post to publish. All examples are personally tested and shared on GitHub. Use these examples to motivate yourself to benefit others. At the same time, all the posts in this series will be published in the blogger personal public search "Love Ape" or "ape_it" to facilitate reading. If there is any infringement of the original rights of the author, please inform the blogger in time to delete if the reader has objections to the content of the text or questions are welcome through the blog post or public messages and other ways to discuss together.

Source code Address Https://github.com/rocwinger/java-disabuse




This article from "Winger" blog, declined reprint!

What's going on with the Java Java Builder?

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.