Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initialisers

 
Tony kunds
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can some one explain me the below statement if possible with a example.
If any checked exception thrown during execution of initializer expresion it must be caught & handled with in initializer expresion.
-Thanks
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code will not compile, due to an unchaught exception in an initializer:

However, the following code will compile, because the checked exception is handled within the initializer:

I hope that helps,
Corey
 
Reid M. Pinchback
Ranch Hand
Posts: 775
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to fill out the rationale behind the code, here is what you need to keep in mind. I'm always going to be talking about checked exceptions, since those are the only ones relevant to your question.
When you write a method, e.g. "foo()", if it can throw an exception you must either handle the exception within the method or declare the exception in the signature of the method:

When you have an initializer, there is no method, so no way to declare the exception. What do you do? Two cases:
1. For an free-floating instance initialization block, you still have two choices. You can either handle the exception in the block, *or* you can declare the exception as being thrown by all the constructors.
2. For a free-floating static initialization block, you only have one choice. There is no magic place to pass along the exception. You must handle the exception within the block.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic