简体   繁体   English

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

[英]I can't throw NoRouteToHostException even with catch(Exception e)

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. 因此,如果无法建立连接,我尝试使用此虚拟方法返回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;
 }

However, I got this error instead of catching a exception (and be able to return false) 但是,我得到此错误而不是捕获异常(并且能够返回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??? 而且我不能java.net.NoRouteToHostException:没有路由到主机:即使使用catch(Exception e)也连接异常为什么catch(Exception e)无法捕获此异常?

The error line guide me to Object objData = urlConnect.getContent(); 错误行将我引导至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. 这是一个Jbutton,它是一个Log_in按钮。

This jbutton, when click, will try to connect to the server my instructor set up for our work. 单击此jbutton时,它将尝试连接到我的老师为我们的工作设置的服务器。 I use the isreachable() to check if I can connect to the Internet before actually trying to connect to the actual server. 在实际尝试连接到实际服务器之前,我使用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();
            }
        }


    });

You are not throwing any exceptions. 您不会抛出任何异常。

You are catching all of them, then printing the stack and returning false. 您正在捕获所有这些,然后打印堆栈并返回false。

The following method declaration would throw the NoRouteToHostException exception. 以下方法声明将引发NoRouteToHostException异常。

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; 将捕获NoRouteToHostException; as NoRouteToHostException extends IOException. 因为NoRouteToHostException扩展了IOException。

If you removed the catch for IOException, it would be caught by the Exception catch as IOException extends Exception. 如果删除了IOException的捕获,则当IOException扩展Exception时,它将被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) NoRouteToHostException类具有以下层次结构(父级到子级)

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. 因此,当引发任何异常时,它将首先查找其catch类型,如果未找到,则遵循从子级到父级的层次结构。

So your exception is definitely caught inside your below catch block 因此,您的异常情况肯定被捕获在下面的catch块中

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

just put System.out.println("exception caught"); 只需将System.out.println("exception caught"); it inside the above catch block, you would definitely see the catch of exception. 在上面的catch块中,您肯定会看到异常的catch。

if you want to throw the exception caught then you must use throw keyword at the appropriate place. 如果要抛出捕获的异常,则必须在适当的位置使用throw关键字。

so to throw NoRouteToHostException exception,just put throw inside exact catch block as below and add throws NoRouteToHostException after method name. 因此要抛出NoRouteToHostException异常,只需将throw放入如下的确切catch块中,并在方法名称后添加throws NoRouteToHostException

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM