1

Hy ... I have the following code :

    try { Nrtrde record = new Nrtrde(); }
    catch (Exception e) {
        System.out.println(" ERROR\n");
        e.printStackTrace(); }
    finally { Nrtrde record = new Nrtrde(); System.out.println(" OK\n"); }

record.setSpecificationVersionNumber(specificationVersionNo);

and when compiling i get the following error :

NRTRDE\ENCODER.java:28: error: cannot find symbol
        record.setSpecificationVersionNumber(specificationVersionNo);
        ^
  symbol:   variable record
  location: class ENCODER
1 error

It seems I cannot create an object insinde a try {} and use it outside try {} ..

Why ?

Thank you

pufos
  • 2,890
  • 8
  • 34
  • 38

5 Answers5

5

You have to declare it outside the block, but you can initialize it inside the block:

Nrtrde record = null;
try { 
    record = new Nrtrde();
} catch (SomeException e) {
    // handle exception here
}
if(record!=null){
    // do something with it
}

In Java, {} are block delimiters. Nothing is visible outside the block it is defined in. (Class members are an exception to this rule if the visibility allows it).

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
3

Because its scope is limited to {}. It wont be recognized outside. Thats why you are getting this error

Habib
  • 219,104
  • 29
  • 407
  • 436
2

You are correct in that case your object will exist until you program will exit the try block. That is because it is scoped by the {}

To make it visible both in the try and finally/catch do something like:

Nrtrde record;
 try { record = new Nrtrde(); }
    catch (Exception e) {
        System.out.println(" ERROR\n");
        e.printStackTrace(); }
    finally { record = new Nrtrde(); System.out.println(" OK\n"); }
Bogdan Emil Mariesan
  • 5,529
  • 2
  • 33
  • 57
0

Your record variable is visible only within the try and finally block, you have to declare your Nrtrde before the try-catch-finally block.

Kojotak
  • 2,020
  • 2
  • 16
  • 29
0

A variable can be acccessed only between a pair of curly braces { }.

http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm

MattAllegro
  • 6,455
  • 5
  • 45
  • 52
Achintya
  • 11
  • 1