开发者

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


Document d = null;

instead of just

Document d;

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


Try:

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


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.


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();
}


Should be:

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


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜