即使使用catch(Exception e),我也无法抛出NoRouteToHostException

时间:2014-05-01 16:53:24

标签: java exception try-catch

我被指派制作方法来检查互联网是否可以访问。 因此,如果无法连接,我会尝试使用此伪方法返回false。

 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;
 }

但是,我收到此错误而不是捕获异常(并且能够返回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)

我无法解决java.net.NoRouteToHostException:没有到主机的路由:连接异常甚至是catch(例外e) 为什么catch(异常e)无法捕获此异常???

错误行指导我对象objData = urlConnect.getContent(); 但是这个尝试内部应该被捕获了吗?

编辑:这是调用此方法的代码。 它是一个Jbutton,它是一个Log_in按钮。

这个jbutton,当点击时,将尝试连接到我的教师为我们的工作设置的服务器。在实际尝试连接到实际服务器之前,我使用isreachable()来检查是否可以连接到Internet。

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();
            }
        }


    });

2 个答案:

答案 0 :(得分:0)

你没有抛出任何例外。

您正在捕获所有,然后打印堆栈并返回false。

以下方法声明会抛出NoRouteToHostException异常。

public static boolean isInternetReachable() throws NoRouteToHostException {
 //Your code (that calls something that also throws NoRouteToHostException)
}

你不需要捕获异常只是为了抛出它。


以下内容:

}catch(IOException e){ 

}

将捕获NoRouteToHostException;因为NoRouteToHostException扩展了IOException。

如果删除了IOException的catch,它将被Exception catch捕获,因为IOException扩展了Exception。

}catch(Exception e){ 

}

这将捕获所有异常,检查和取消选中。所以你肯定会抓住异常,但你不会抛弃它。

答案 1 :(得分:0)

NoRouteToHostException具有以下层次结构(子命令的父级)

java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.net.SocketException
java.net.NoRouteToHostException

因此,当抛出任何异常时,它首先查找其catch类型,如果没有找到,它将遵循从子级到父级的层次结构。

所以你的异常肯定会在你的下面的catch块中被捕获

catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         return false;
     }

只需将System.out.println("exception caught");放在上面的catch块中,你肯定会看到异常的捕获。

如果要抛出捕获的异常,则必须在适当的位置使用throw关键字。

所以要抛出NoRouteToHostException异常,只需将throw放入精确的catch块中,如下所示,并在方法名后添加throws NoRouteToHostException

 catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
           throw new NoRouteToHostException();
            // return false; remove return
         }