2

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?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Jeff Lamb
  • 5,755
  • 4
  • 37
  • 54

3 Answers3

5

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");
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 3
    If you do that, you definitely need to add an if statement to check if `fetcher` is null outside of the try-catch. The alternative is to move the return statement within the try block and do some action if an exception is raised (such as rethrow the exception, return null, etc) – Mark Peters Feb 09 '11 at 23:46
  • Yes. Thanks for the improvement! – Hovercraft Full Of Eels Feb 09 '11 at 23:48
1

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>";
}
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
1

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680