Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / May 2007

Tip: Looking for answers? Try searching our database.

Initializing final variables

Thread view: 
Christoph Burschka - 10 May 2007 08:37 GMT
I'm declaring a constant object in my class definition, whose
constructor throws an exception. Note that the exception never actually
gets thrown - my argument ensures that.

Apparently, I can't use try-catch blocks outside a method, so I can't
initialize this value in the class declaration. But if I don't
initialize it there, I can't declare it final.

Does this just mean I can't initialize final variables with
exception-throwing constructors, or is there a solution?

--cb
Tom Hawtin - 10 May 2007 09:00 GMT
> I'm declaring a constant object in my class definition, whose
> constructor throws an exception. Note that the exception never actually
[quoted text clipped - 3 lines]
> initialize this value in the class declaration. But if I don't
> initialize it there, I can't declare it final.

    private static final MyClass thing;
    static {
        try {
            thing = new MyClass();
        } catch (SomeException exc) {
            throw new Error();
        }
    }

or

    private static final MyClass thing = makeThing();
    private static MyClass MakeThing() {
        try {
            return new MyClass();
        } catch (SomeException exc) {
            throw new Error();
        }
    }

Tom Hawtin


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.