Cannot find symbol error [duplicate]
Let me first apologize. I've been coding for a long time now, but I'm new to Java. I feel like this should be a simple error, but I've been working on it for a half hour to no avail:
public String getHtml(HttpServletRequest request) {
try {
WebPageFetcher fetcher = new WebPageFetcher("http://google.com");
} catch (Exception e) {
log.error("WebPageFetcher failed ...");
}
return "<div id=\"header\">" + fetcher.getPageContent() + "</div>";
}
Where WebPageFetcher is implemented as shown here: 开发者_运维知识库http://www.javapractices.com/topic/TopicAction.do?Id=147
I'm getting an error:
cannot find symbol
symbol : variable fetcher
location: class myclass
What am I doing wrong?
fetcher is visible only in the block where it was declared, the try block. Try declaring before the block so it will be visible throughout the method:
WebPageFetcher fetcher = null;
try {
fetcher = new WebPageFetcher("http://google.com");
}
The lifetime of the variable fetcher
is only within the most enclosing scope, i.e. the most nested pair of brace ({ }
) surrounding it. Therefore, it no longer exists by the time you get to the return
statement where you're trying to use it.
On the return the variable fetcher
is out of scope.
Try:
public String getHtml(HttpServletRequest request) {
try {
WebPageFetcher fetcher = new WebPageFetcher("http://google.com");
// return within scope
return "<div id=\"header\">" + fetcher.getPageContent() + "</div>";
} catch (Exception e) {
log.error("WebPageFetcher failed ...");
}
return /*something that make sense*/ "<html>500</html>";
}
精彩评论