Initializing final variables

Discussion in 'Java' started by Christoph Burschka, May 10, 2007.

  1. 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
    Christoph Burschka, May 10, 2007
    #1
    1. Advertising

  2. Christoph Burschka

    Tom Hawtin Guest

    Christoph Burschka wrote:
    > 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.


    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
    Tom Hawtin, May 10, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Adam Smith
    Replies:
    0
    Views:
    475
    Adam Smith
    Apr 15, 2004
  2. =?Utf-8?B?ZG90bmV0dGVzdGVy?=

    Initializing variables in a class

    =?Utf-8?B?ZG90bmV0dGVzdGVy?=, Nov 23, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    425
    Peter Rilling
    Nov 23, 2005
  3. JFCM
    Replies:
    4
    Views:
    5,712
  4. Neil Zanella

    initializing static class variables

    Neil Zanella, Jul 30, 2004, in forum: C++
    Replies:
    11
    Views:
    779
    Neil Zanella
    Aug 8, 2004
  5. Replies:
    5
    Views:
    496
    Chris Uppal
    Nov 17, 2006
Loading...

Share This Page