I am trying to return a String from the following method.
public String openCon() {
try {
Scanner scan = new Scanner(System.in);
URL sitex = new URL("http://" + scan.nextLine());
URLConnection connection = sitex.openConnection();
Object content = sitex.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(sitex.openStream()));
String str;
String x = "1";
while ((str = in.readLine()) != null) {
x += str;
}
in.close();
return x;
}
catch(Exception e) {
System.out.println(e);
}
}
The problem isn’t returning from the
tryblock – the problem is that you aren’t returning anything if an exception is thrown. You’re catching the exception… but then reaching the end of the method without returning anything. (To put it in more technical terminology: the end of a non-void method should not be reachable.)Personally, I would just remove the
catchblock entirely, and addthrowsdeclarations for any exceptions which are thrown within the body. You’re not really handling the exceptions – you’re just printing them out and ignoring them, which is very rarely a good idea. CatchingExceptionis usually a pretty bad idea to start with.As an aside, you should also close your
BufferedReaderandURLConnectionvalues in afinallyblock so they’re closed even in the case of an exception. I’d also suggest either passing a fixed encoding name toInputStreamReader, or using a higher-level HTTP client API which will use the content-type header from the response. Oh, and useStringBuilderinstead of string concatenation in a loop.