4 Replies Latest reply: Jun 4, 2012 11:45 AM by aksarben RSS

    how to check / internet is working or not?

    rohit007
      i need to execute a line of code in java console application only and only when internet is working ie i can access the google page
      to check the internet connection , i try below code,,
      try
              {
              URL url = new URL("http://google.com/");
                 URLConnection connection = url.openConnection();
                 connection.connect();
               
              }
              catch( Exception ex)
              {
                  // connection can not be established 
              }
      but here, when internet is working, try block successfully execute . when internet is down , it throw an exception on Connection.connect() ,
      connect() is void type , it is not returning anything, that's why i can not handle it.... is there any other way , where i get true or false or any number , when internet is ok, ie www.google.com is responseing..
        • 1. Re: how to check / internet is working or not?
          796440
          rohit pathak wrote:
          iwhen internet is down , it throw an exception on Connection.connect() ,
          connect() is void type , it is not returning anything, that's why i can not handle it
          When an exception is thrown, you have two choices:

          1) Catch it and actually handle it. This means whatever failed, you have to make it work. Maybe by trying again, maybe be providing a default value.

          2) If you cannot to #1, then you should not catch the exception in the first place. Or, if you do catch it, wrap it and rethrow it.

          So, for example, in your case, if your code is:
          Establish connection.
          Use connection.
          If the "establish" part fails, you obviously can't do the "use" part, and this overall task has failed. That happens sometimes.
          • 2. Re: how to check / internet is working or not?
            EJP
            connect() is void type , it is not returning anything, that's why i can not handle it
            You can handle it. What exactly do you think the IOException is for?
            is there any other way
            You don't need another way. You have a way. Catch the exception.
            • 3. Re: how to check / internet is working or not?
              morgalr
              rohit pathak wrote:
              ... connect() is void type , it is not returning anything, that's why i can not handle it....
              Don't confuse throwing an Exception with returning data... it's not the same thing.
              • 4. Re: how to check / internet is working or not?
                aksarben
                Another alternative: Just look out the window. If the sun has turned black, and the moon is red, the Internet has stopped working!