user680406
user680406

Reputation: 5747

Question about try catch statement

If I write this code:

Document d = searcher.doc(docId);
d.get("latitude")

I get

unreported exception ... must be caught or declared to be thrown

If I write this,

try {
    Document d = searcher.doc(docId);
}
d.get("latitude")

I obviously get:

cannot find symbol
symbol  : variable d

If I write this

Document d;
try {
d = searcher.doc(docId);
}
d.get("latitude");

I get this:

variable d might not have been initialized

Since I don't want to extend try/catch to all document how can I solve this issue ?

thanks

Upvotes: 0

Views: 162

Answers (7)

Jean-Bernard Pellerin
Jean-Bernard Pellerin

Reputation: 12670

Document d = null;

instead of just

Document d;

Though then you have to worry about NullPointerException later down the road when you use d

Upvotes: 4

ILMTitan
ILMTitan

Reputation: 11017

If your catch causes the rest of the method to skip (by either a return or throw statement), or if you initialize d in the catch, you should not get this error. .

Document d;
try {
    d = searcher.doc(docId);
} catch (SomeException e) {
    return null;
    //throw new RuntimeException(e);
    //d = some default value
}
d.get("latitude");

Just initializing d = null will simply cause a null pointer when your exception does occur (obscuring the actual cause).

Upvotes: 0

kamaci
kamaci

Reputation: 75137

You should initialize your variable and catch exception (you can change the exception name and getting message level according to your needs).

Document d = null;
try {
   d = searcher.doc(docId);
   d.get("latitude");
} catch (Exception ex){
   ex.getMessage();
}

Upvotes: 1

Paul Creasey
Paul Creasey

Reputation: 28834

You can just initialize it to null, but you shouldn't in my opinion.

If the method throws an exception then d == null, so you either need to handle that case with if (d != null) or just scope d inside the try block.

I'd do the latter.

Upvotes: 0

lukastymo
lukastymo

Reputation: 26809

Should be:

Document d = null;
try {
    d = searcher.doc(docId);
} catch (Exception e) {
    //...
}
d.get("latitude");

Upvotes: 0

yan
yan

Reputation: 20982

Try:

Document d = null;
try {
   d = searcher.doc(docId);
   d.get("latitude");
}

Upvotes: 3

Adi
Adi

Reputation: 5223

You do what the message says: Just initialize your variable "d" with null at the beginning:

Document d = null;
try {
  d = searcher.doc(docId);
}
d.get("latitude"); 

Anyway, beware! if an exception occurs, your "d" variable will be null and you will get an object reference not set exception! Either include the d.get("latitude"); in try block or check for null before calling that line.

Upvotes: 2

Related Questions