8

Very short question: Is there a more elegant way to do this:

Object tmp;
try {
 tmp = somethingThatCanFail();
} catch (Fail f) {
 tmp = null;
}
final Object myObject = tmp;
// now I have a final myObject, which can be used in anonymous classes
1

3 Answers 3

12

You could extract the creation of the value in its own method:

final Object myObject = getObjectOrNull();

public Object getObjectOrNull() {
  try{
    return somethingThatCanFail();
  } catch (Fail f) {
    return null;
  }
}

It's longer, but depending on your definition of "elegant" it might be more elegant.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 but anyway final is just a security but you can deal without it no?
final is a very useful tool to document and enforce invariants. Additionally it is sometimes required when interacting with anonymous inner classes.
It also supposedly helps the compiler with optimization, but I guess it can do enough of that on its own.
AFAIK the finally flag on local variables is only checked by the compiler, it does not exist in the bytecode and so cannot be used by hotspot. Of course hotspot might still notice that variables are not modified and generate better code.
0

Depends what you mean by "this" (and "more elegant")

I'm not sure why you think you need tmp AND myObject, but there's no way to avoid having one of those declarations outside the try block IF you want to access it in the catch block.

What's wrong with

Object myObject = null;
try {
  myObject = somethingThatCanFail();
} catch (Fail f) {
  // do nothing because we can deal with myObject being null just fine
}

2 Comments

I think the question is explicitly about assigning a final variable.
Yeah, the pre-edited version forgot to mention that really important requirement!
0

These days I tend to do it like this

final Thingy zeFing; {
    Thingy t = null;
    try {
        t = somethingThatCanFail();
    } catch (CurveBall f) {
        // log...
    }
    zeFing = t;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.