Welcome to the Java Programming Forums


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.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: throws in main?

  1. #1
    Member
    Join Date
    Jul 2012
    Location
    Dallas area
    Posts
    34
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default throws in main?

    Before I ask my question I need to say that the following code in question is not my own. It is from Oracle's Java Tutorial. This mini-program finds a web page and prints its source code.

    My question is: How can the main method use a throws statement if main is the only method in the program? In other words, where is the try-catch block that main throws to?

    Here's the code:

     
    import java.net.*;
    import java.io.*;
     
    public class URLReader
    {
        public static void main(String[] args) throws Exception
        {
     
            URL url = new URL("http://www.yourURL.com/");
            BufferedReader in = new BufferedReader(
            new InputStreamReader(url.openStream()));
     
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();
        } // end main
    } // end class URLReader

    Please explain where the throws is caught.


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: throws in main?

    Same place the rest of the code is which called main.

  3. #3
    Member
    Join Date
    Jul 2012
    Location
    Dallas area
    Posts
    34
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: throws in main?

    Which is where?

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: throws in main?

    These types of questions in your favorite search engine will provide a wealth of information to browse. Search keywords "java jvm main method" and the like.

  5. #5
    Member
    Join Date
    Jul 2012
    Location
    Dallas area
    Posts
    34
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: throws in main?

    The program, as it is shown above, compiles and runs as it should. So is the "rest of the code" in the imported classes?

  6. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: throws in main?

    No.
    Did you try the search?

  7. #7
    Member
    Join Date
    Jul 2012
    Location
    Dallas area
    Posts
    34
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: throws in main?

    Yes, which is why I turned to the forum for help. I searched the forum, too.

  8. #8
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: throws in main?

    Quote Originally Posted by pict3000 View Post
    ...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:

    In other words change line 6 from
        public static void main(String[] args) throws Exception

    to the following:

        public static void main(String[] args)

    Now compile and what do you get?

    Well...

    Here's what the compiler tells me:
    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
    import java.net.*;
    import java.io.*;
     
    public class Z
    {
        public static void main(String[] args)
        {
     
            URL url = null; // Must be declared outside of the block so that the compiler won't complain
            try {
                // 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 = new URL("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 MalformedURLException
            System.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 point
            try {
     
                BufferedReader in = new BufferedReader( new InputStreamReader(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 = new URL("//xxxzaphodsxxx.info/");

    Here's what I see:
    Bad URL syntax
    java.net.MalformedURLException: no protocol: //xxxzaphodsxxx.info/
            at java.net.URL.<init>(URL.java:583)
            at java.net.URL.<init>(URL.java:480)
            at java.net.URL.<init>(URL.java:429)
            at Z.main(Z.java:18)
    Tttthat's all, Folks!

    Now go back to the original code (with main(...) throws Exception) and no try{}catch(){} blocks and use the url examples that I showed above.


    Cheers!

    Z
    Last edited by Zaphod_b; October 4th, 2012 at 01:42 PM.

  9. #9
    Member
    Join Date
    Jul 2012
    Location
    Dallas area
    Posts
    34
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default 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.

    You've freed me from my menacing confusion.

    Kudos to you!!!

  10. #10
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: throws in main?

    Quote Originally Posted by pict3000 View Post
    ...freed...from...confusion.
    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...)


    Cheers!

    Z

  11. #11
    Member
    Join Date
    Jul 2012
    Location
    Dallas area
    Posts
    34
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: throws in main?

    Well, thank you. I sure will. This forum needs folks like you.

    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.

    Have a great day, Zaphod_b!

Similar Threads

  1. [SOLVED] TableRowSorter throws Exception
    By Onur in forum AWT / Java Swing
    Replies: 1
    Last Post: November 7th, 2013, 06:23 AM
  2. throws Exceptions
    By beruska in forum Exceptions
    Replies: 1
    Last Post: October 25th, 2011, 02:25 PM
  3. Executing commands throws an InterruptedException even with waitFor()
    By LilaH in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 20th, 2011, 03:57 AM
  4. ZipInputStream Throws Illegalargument exception for diacritics
    By meghaladevi in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: October 12th, 2010, 02:32 AM
  5. [SOLVED] File.createTempFile() throws exception on Win7
    By jitinsingla in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: September 10th, 2010, 02:14 PM

Tags for this Thread