I am assign to make a method to check if the internet is reachable or not. So I try this dummy method to return false if connection is not possible.
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
urlConnect.setConnectTimeout(1000);
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
However, I got this error instead of catching a exception (and be able to return false)
java.net.NoRouteToHostException: No route to host: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URLConnection.getContent(Unknown Source)
at log2.isInternetReachable(log2.java:59)
at log2$7.actionPerformed(log2.java:319)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
And I can't the java.net.NoRouteToHostException: No route to host: connect exception even with catch(Exception e) Why catch(Exception e) cannot catch this exception???
The error line guide me to Object objData = urlConnect.getContent(); but that's inside the try so should it be catched????
Edit: this is the code that call this method. It's a Jbutton that is a Log_in button.
This jbutton, when click, will try to connect to the server my instructor set up for our work. I use the isreachable() to check if I can connect to the Internet before actually trying to connect to the actual server.
public class log2 extends JPanel {
>
>
public static boolean isInternetReachable()
{
>
>
>
}
JButton blogin;
>
>
>
public log2(final DaGame Dagame) throws IOException {
connection = true; // this is to prevent the repaint(); to draw it incorrectly when other method was call first.
>
> Many other code.
>
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final JDialog d = new JDialog(Dagame);
connection = isInternetReachable();
if (connection){
final SwingWorker<?, ?> worker = new SwingWorker<Void, Integer>() {
@Override
protected Void doInBackground() throws Exception {
d.setLocationRelativeTo(Dagame);
d.setLocation(Dagame.getWidth() / 3, Dagame.getHeight() / 3);
d.setModal(true);
d.setSize(300, 300);
d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final JPanel mainPanel = new JPanel(new BorderLayout()) {
@Override
protected void paintComponent(Graphics g) {
File file = new File("C:/AppPro/picture/loading1.gif");
ImageIcon b = new ImageIcon(file.getAbsolutePath());
aImage = b.getImage();
super.paintComponent(g);
g.drawImage(aImage, 0, 0, getWidth(), getHeight(), this);
g.drawString(str, (getWidth() / 3) , 3*(getHeight() / 4));
}
};
d.getContentPane().add(mainPanel);
d.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
System.out.println("closennnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn\nnnnnnnnnnnnnnnnnnnnnnn\nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn\n\n\n\n\n\n");
//worker.cancel(true);
}
@Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
});
String puname = txuser.getText();
String ppaswd = pass.getText();
String login = "login&user=" + puname;
String pass_string = "pass=" + ppaswd;
// login&user=524&pass=72463
String ID = login + "&" + pass_string;
String url = "http://128.199.235.83/icw/?q=icw/service/"
+ ID;
try {
URL u = new URL(url);
InputStream x;
x = new URL(url).openStream();
HttpURLConnection con = (HttpURLConnection) u
.openConnection();
con.connect();
Scanner wb = new Scanner(con.getInputStream());
String c = "";
while (wb.hasNext()) {
c = wb.nextLine();
}
if (c.indexOf("\"status\":0") != -1) {
connection = true;
//System.out.print("quit");
//connection = false;
// BufferedImage in = ImageIO.read(new
// File("C:/AppPro/picture/yugi.jpg"));
// ImageIcon abc = new ImageIcon(in);
// optionPane = new JOptionPane();
// optionPane.showMessageDialog(null,
// "Incorrect username or password", "Fail",
// JOptionPane.INFORMATION_MESSAGE, abc);
// txuser.setText("Incorrect Password or Username");
// pass.setText("");
// music();
} else {
connection = true;
System.out.print("welcome");
String ei = txuser.getText();
int id = Integer.parseInt(ei);
Dagame.setUser(id);
/*
INW userA = new INW (Integer.parseInt(ID));
DaGame.userName=userA.getFirstName();
DaGame.userSurname = userA.getLastName();
DaGame.userLP=userA.getFlp();
DaGame.userMP=userA.getFmp();
Dagame.userPic = userA.getfbPic();
*/
String ff="";
char[] pp =pass.getPassword();
for(int i=0;i<pp.length;i++){
char f = pp[i];
ff +=f;
}
int passWord = Integer.parseInt(ff);
Dagame.setPassword(passWord);
System.out.println(passWord);
String d = c;
d=d.substring(d.indexOf("firstname_en")+14);
d=d.substring(1, d.indexOf(",")-1);
System.out.println(d);
String sf = c;
sf=sf.substring(sf.indexOf("lastname_en")+13);
sf=sf.substring(1, sf.indexOf(",")-1);
System.out.println(sf);
String l = c;
l=l.substring(l.indexOf("full_lp")+9);
l=l.substring(1, l.indexOf(",")-1);
System.out.println(l);
int tempp = Integer.parseInt(l);
String m = c;
m=m.substring(m.indexOf("full_mp")+9);
m=m.substring(1, m.indexOf(",")-1);
System.out.println(m);
int temppp = Integer.parseInt(m);
String fb = c;
fb=fb.substring(fb.indexOf("fb_id")+7);
fb=fb.substring(1, fb.indexOf(",")-1);
System.out.println(fb);
URL fburl = new URL("https://graph.facebook.com/"+fb+"/picture");
Image im = ImageIO.read(fburl);
if(im==null){
System.out.println("Image is null1");
}
DaGame.userPic=im;
if(im==null){
System.out.println("Image is null2");
}
DaGame.userName=d;
DaGame.userSurname = sf;
DaGame.userLP=tempp;
DaGame.userMP=temppp;
Dagame.setDeckUser();
Dagame.setDeckUser();
str = "Loading Card";
mainPanel.repaint();
// newframe ri = new newframe();
// ri.setVisible(true);
Main_Menu_UI abc = new Main_Menu_UI(Dagame);
Dagame.addCard(abc);
// dispose();
}
if (c.indexOf("\"status\":0") != -1) {
System.out.print("quit");
// optionPane = new JOptionPane();
// optionPane.showMessageDialog(null,
// "Incorrect username or password", "Fail",
// JOptionPane.INFORMATION_MESSAGE, abc);
// txuser.setText("Incorrect Password or Username");
// pass.setText("");
// timeStart();
incorrect = true;
numIncorrect++;
if (numIncorrect == 3) {
txuser.setEnabled(false);
pass.setEnabled(false);
blogin.setEnabled(false);
}
//repaint();
} else {
System.out.print("welcome");
// newframe ri = new newframe();
// ri.setVisible(true);
Main_Menu_UI abc = new Main_Menu_UI(Dagame);
Dagame.addCard(abc);
// dispose();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repaint();
//repaint();
}
return null;
}
protected void done() {
d.dispose();
}
};
worker.execute();
d.setVisible(true);
repaint();
}
else if (!connection){
repaint();
}
}
});
You are not throwing any exceptions.
You are catching all of them, then printing the stack and returning false.
The following method declaration would throw the NoRouteToHostException exception.
public static boolean isInternetReachable() throws NoRouteToHostException {
//Your code (that calls something that also throws NoRouteToHostException)
}
You do not need to catch the exception just to throw it.
The following:
}catch(IOException e){
}
Will catch the NoRouteToHostException; as NoRouteToHostException extends IOException.
If you removed the catch for IOException, it would be caught by the Exception catch as IOException extends Exception.
}catch(Exception e){
}
This will catch all exceptions, checked and unchecked. So you are definitely catching the exception, but you are not throwing it.
Class NoRouteToHostException
has the below hierarchy(parent to child order)
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.net.SocketException
java.net.NoRouteToHostException
so when any exception is thrown , it looks for its catch type first,if not found it follows the hierarchy from child to parent.
So your exception is definitely caught inside your below catch block
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
just put System.out.println("exception caught");
it inside the above catch block, you would definitely see the catch of exception.
if you want to throw the exception caught then you must use throw keyword at the appropriate place.
so to throw NoRouteToHostException exception,just put throw inside exact catch block as below and add throws NoRouteToHostException
after method name.
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new NoRouteToHostException();
// return false; remove return
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.