File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Initialisers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Initialisers" Watch "Initialisers" New topic


Tony kunds

Joined: Apr 25, 2002
Posts: 25
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.
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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,

SCJP Tipline, etc.
Reid M. Pinchback
Ranch Hand

Joined: Jan 25, 2002
Posts: 775
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.

Reid - SCJP2 (April 2002)
I agree. Here's the link:
subject: Initialisers
It's not a secret anymore!