BufferedReader Initialization hangs?

I'm trying to read content from the web(more specifically wikipedia) and whenever it's a wiki page that doesn't exist(ie. http://en.wikipedia.org/wiki/Asdfasdfasdfasdf) my BufferedReader hangs on init. I've narrowed it down to init and not readLine() which I find weird. My code is as follows:

URL url = new URL("http://en.wikipedia.org/wiki/" + query.replace(" ", "_"));
URLConnection connection = url.openConnection();
BufferedReader wikiReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

Any code after the init of wikiReader never executes however this isn't a problem with wiki pages that exist...any help would be appreciated.

Jon Skeet
people
quotationmark

I strongly suspect that it's not hanging - it's just throwing an exception without you noticing. I'd expect it to throw a FileNotFoundException, which is what happens when I tried it.

It's happening before readLine() because getInputStream() is going to make the HTTP request, and that's failing. It's never getting as far as the BufferedReader constructor itself - you can see this if you change the code to:

InputStream inputStream = connection.getInputStream();
// You won't get to here whne the page doesn't exist
BufferedReader wikiReader = new BufferedReader(new InputStreamReader(inputStream));

Basically, you need to look at where in your stack you're catching exceptions... and make sure it's appropriate. For a start, you should make sure you're logging the exception, and then work out what you want to do afterwards... that will very much depend on what your application does.

people

See more on this question at Stackoverflow