The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Re: throws in main?

Originally Posted by pict3000

...why I turned to the forum for help...

Hmmm... Let me summarize another user's similar experience:

1. Googled "java programming forum help" First non-advertising hit was this forum. This must be the best, right?
2. Signed up for this forum. Read forum rules. Posted specific question about some code. Put code in code tags. Was told to use Google.

Annoying, isn't it?

Anyhow...

Try to compile the example but leave off the part about main(...) throws Exception:

URLReader.java:11: unreported exception java.net.MalformedURLException; must be caught or declared to be thrown
url = new URL("http://www.xxxzaphodsxxx.com/");
^
URLReader.java:13: unreported exception java.io.IOException; must be caught or declared to be thrown
BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream()));
^
URLReader.java:16: unreported exception java.io.IOException; must be caught or declared to be thrown
while ((inputLine = in.readLine()) != null)
^
URLReader.java:18: unreported exception java.io.IOException; must be caught or declared to be thrown
in.close();

See: It is telling me that some of the methods used in main() can throw exceptions. The compiler insists on telling me this. Furthermore, it won't even compile the program unless I "do something" about it. I either have to catch the exceptions that it flagged, or I can declare something about the exceptions.

If you don't want to be bothered putting try{}catch(){} blocks around the flagged method calls in your program, you can reassure the compiler that you recognize the situation by putting the generic "throws Exception" thing in the main() declaration.

Then, any exception thrown by an underlying method can be "caught" here (in main) and passed along. Some people (who don't know about decisions that went into defining the language) have suggest that it might have been less confusing if the terminology said something about main "catches" exceptions rather than main "throws" exceptions. Makes no difference what we think. Gotta follow the rules.

Anyhow...

Now, if an exception occurs from any underlying method and we don't catch it, the throwee will print a generic message and abort the program. Maybe that's good enough.

On the other hand, if you want to supply additional information before bailing out of the program or if you want to handle the exception in a way that gives the program a chance to recover, that's what the try{}catch(){} stuff is all about.

Note that ou can also give a comma-separated list of the exceptions that you will not catch and write try{}catch(){} blocks for the others. Etc., etc., etc.

Note that, even with that generic "throws Exception" thing you can still write specific try{}catch(){} blocks for specific method calls in your program. Continue on with the tutorial and if you have further questions, try posting again.

Oh, yeah. About that example code that you posted...

Now here's something interesting (interesting to me, that is) that I found when running it.

Note that, apparently because of the popularity of that tutorial, someone has actually snagged that URL shown in the example code, and you may not get an exception if you run it as shown. (At least I didn't. A server at yourURLcom actually responded. Brilliant!)

So...

If you actually want to see an exception, try a url something like http://xxxzaphodsxxx.info[ in the program

Anyhow...

If you are still interested, you can play around with something like

importjava.net.*;importjava.io.*;publicclass Z
{publicstaticvoid main(String[] args){URL url =null;// Must be declared outside of the block so that the compiler won't complaintry{// Checks syntax of URL expression; doesn't check to see if it// can be reached// This valid url syntax, but no server can be reached here
url =newURL("http://xxxzaphodsxxx.info/");// For testing: Give something that it can't handle// Malformed URL: No protocol given//url = new URL("//xxxzaphodsxxx.info/");}catch(MalformedURLException e){System.out.println("Bad URL syntax");
e.printStackTrace();System.out.println("Tttthat's all, Folks!");System.exit(1);}// End catch MalformedURLExceptionSystem.out.println("After instantiating url");// A single block that surrounds all IO// Not necessarily the best thing to do in general, but it's easy to make a pointtry{BufferedReader in =newBufferedReader(newInputStreamReader(url.openStream()));String inputLine;while((inputLine = in.readLine())!=null)System.out.println(inputLine);
in.close();}catch(IOException e){System.out.println("Bummer: BAD IO");
e.printStackTrace();System.exit(1);}// End catch IOException}// end main()}// end class URLReader

My output:

After instantiating url
Bummer: BAD IO
java.net.UnknownHostException: xxxzaphodsxxx.info
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:175)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:546)
at java.net.Socket.connect(Socket.java:495)
at sun.net.NetworkClient.doConnect(NetworkClient.java:178)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:409)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:530)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:240)
at sun.net.www.http.HttpClient.New(HttpClient.java:321)
at sun.net.www.http.HttpClient.New(HttpClient.java:338)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:935)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:876)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:801)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1139)
at java.net.URL.openStream(URL.java:1029)
at Z.main(Z.java:31)

If I comment out the good url line and uncomment the bad url line

//url = new URL("http://xxxzaphodsxxx.info/");// For testing: Give something that it can't handle// Malformed URL: No protocol given
url =newURL("//xxxzaphodsxxx.info/");

Re: throws in main?

I can't thank you enough, Zaphod_b!

Until your in-depth response, everywhere else I looked on the web there was no hint of any explanation for why my example had a "throws Exception" in the heading of a main method that did not point to any actual try-catch blocks.

Main is supposed to be where other methods throw for their exception handling! So my example was puzzling.

But you've summed it up by saying the "throws Exception" in main's heading was just a compiler-appeasing shortcut - eliminating the need for Oracle's example to clutter itself with all the usual trying and catching.

Re: throws in main?

Your question was a good one, and your post gave all of the information we needed to explore it with you.

If Mr. Confusion decides to visit you at some later date (like those evil beings in the horror movies---he always comes back), post again.

By running the code you showed us I learned something. (Someone actually paid money to get yourURL.com so that people who run that example are directed to their web site---how strange is that? Do they make money every time someone runs it or what?)

That's why I like to visit this forum. I always learn something. Every single time. Sometimes I learn about Java. Sometimes I learn about life on this small, insignificant planet.

(They told me that I was being sent here not as punishment, but for therapeutic purposes, namely Spiritual Development. I'm working on it. It may take some time...)

Re: throws in main?

As for the reason you and I were sent to this penal colony: The road back to a man's true self is his return from spiritual exile (Saul Bellow - from The Actual). In other words, you're spot on.

About the URL in my example, I actually changed it. It was originally Oracle's homepage URL. I didn't know if it would be frowned upon to post their URL without their permission. But still... We both learned that yourURL.com is active for some odd reason. Your guess is as good as any. I'll bet they were REALLY excited (Eureka!) when that idea popped into their mind - that is until they realized it was just the fourth martini yanking them around again.

I'm so lucky you decided to stop by and answer my question. Until you chimed in, I thought I was going to keep getting swatted with the dumb-dumb bat.