Java 我能';即使使用catch,也不会抛出NOROUTETHOSTEException(异常e)
我被指派做一个方法来检查互联网是否可以访问。 所以,如果连接不可能,我尝试这个虚拟方法返回falseJava 我能';即使使用catch,也不会抛出NOROUTETHOSTEException(异常e),java,exception,try-catch,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
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:没有到主机的路由:connect
位于java.net.DualStackPlainSocketImpl.waitForConnect(本机方法)
位于java.net.DualStackPlainSocketImpl.socketConnect(未知源)
位于java.net.AbstractPlainSocketImpl.doConnect(未知源)
位于java.net.AbstractPlainSocketImpl.connectToAddress(未知源)
位于java.net.AbstractPlainSocketImpl.connect(未知源)
位于java.net.PlainSocketImpl.connect(未知源)
位于java.net.socksocketimpl.connect(未知源)
位于java.net.Socket.connect(未知源)
位于sun.net.NetworkClient.doConnect(未知源)
位于sun.net.www.http.HttpClient.openServer(未知来源)
位于sun.net.www.http.HttpClient.openServer(未知来源)
在sun.net.www.http.HttpClient。(来源不明)
位于sun.net.www.http.HttpClient.New(未知来源)
位于sun.net.www.http.HttpClient.New(未知来源)
位于sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(未知源)
位于sun.net.www.protocol.http.HttpURLConnection.plainConnect(未知源)
位于sun.net.www.protocol.http.HttpURLConnection.connect(未知源)
位于sun.net.www.protocol.http.HttpURLConnection.getInputStream(未知源)
位于java.net.URLConnection.getContent(未知源)
在log2.isInternetReachable(log2.java:59)
在log2$7.actionPerformed(log2.java:319)
在javax.swing.AbstractButton.fireActionPerformed(未知源)
位于javax.swing.AbstractButton$Handler.actionPerformed(未知源)
在javax.swing.DefaultButtonModel.fireActionPerformed(未知源)
位于javax.swing.DefaultButtonModel.setPressed(未知源)
位于javax.swing.plaf.basic.BasicButtonListener.mouseReleased(未知源代码)
位于java.awt.Component.ProcessMouseeEvent(未知源)
位于javax.swing.JComponent.ProcessMouseeEvent(未知源)
位于java.awt.Component.processEvent(未知源)
位于java.awt.Container.processEvent(未知源)
位于java.awt.Component.dispatchEventImpl(未知源)
位于java.awt.Container.dispatchEventImpl(未知源)
位于java.awt.Component.dispatchEvent(未知源)
位于java.awt.LightweightDispatcher.RetargetMouseeEvent(未知源)
位于java.awt.LightweightDispatcher.ProcessMouseeEvent(未知源)
位于java.awt.LightweightDispatcher.dispatchEvent(未知源)
位于java.awt.Container.dispatchEventImpl(未知源)
位于java.awt.Window.dispatchEventImpl(未知源)
位于java.awt.Component.dispatchEvent(未知源)
位于java.awt.EventQueue.dispatchEventImpl(未知源)
位于java.awt.EventQueue.access$200(未知源)
在java.awt.EventQueue$3.run处(未知源)
在java.awt.EventQueue$3.run处(未知源)
位于java.security.AccessController.doPrivileged(本机方法)
位于java.security.ProtectionDomain$1.doIntersectionPrivilege(未知源)
位于java.security.ProtectionDomain$1.doIntersectionPrivilege(未知源)
在java.awt.EventQueue$4.run处(未知源)
在java.awt.EventQueue$4.run处(未知源)
位于java.security.AccessController.doPrivileged(本机方法)
位于java.security.ProtectionDomain$1.doIntersectionPrivilege(未知源)
位于java.awt.EventQueue.dispatchEvent(未知源)
位于java.awt.EventDispatchThread.pumpOneEventForFilters(未知源)
位于java.awt.EventDispatchThread.pumpEventsForFilter(未知源)
位于java.awt.EventDispatchThread.pumpEventsForHierarchy(未知源)
位于java.awt.EventDispatchThread.pumpEvents(未知源)
位于java.awt.EventDispatchThread.pumpEvents(未知源)
位于java.awt.EventDispatchThread.run(未知源)
而且我不能使用java.net.NoRouteToHostException:No route to host:connect异常,即使使用catch(异常e)
为什么catch(异常e)无法捕获此异常
错误行引导我访问对象objData=urlConnect.getContent();
但那是在尝试中,所以它应该被抓住吗
编辑:这是调用此方法的代码。
这是一个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();
}
}
});
公共类log2扩展了JPanel{
>
>
公共静态布尔值IsInternetReach()
{
>
>
>
}
布顿·布洛金;
>
>
>
公共日志2(最终DaGame DaGame)引发IOException{
connection=true;//这是为了防止repaint();在第一次调用其他方法时错误地绘制它。
>
>许多其他代码。
>
addActionListener(新ActionListener(){
已执行的公共无效行动(行动事件ae){
最终JDialog d=新JDialog(Dagame);
连接=ISINTERNETREACABLE();
如果(连接){
最终SwingWorker工人=新SwingWorker(){
@凌驾
受保护的Void doInBackground()引发异常{
d、 setLocationRelativeTo(Dagame);
d、 setLocation(Dagame.getWidth()/3,Dagame.getHeight()/3);
d、 setModal(真);
d、 设置大小(300300);
d、 setDefaultCloseOperation(JDialog.DISPOSE\u ON\u CLOSE);
最终JPanel主面板=新JPanel(新的BorderLayout()){
@凌驾
受保护组件(图形g){
File File=新文件(“C:/AppPro/picture/loading1.gif”);
ImageIcon b=新的ImageIcon(file.getAbsolutePath());
aImage=b.getImage();
超级组件(g);
g、 drawImage(aImage,0,0,getWidth(),getHeight(),this);
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();
}
}
});
public static boolean isInternetReachable() throws NoRouteToHostException {
//Your code (that calls something that also throws NoRouteToHostException)
}
}catch(IOException e){
}
}catch(Exception e){
}
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.net.SocketException
java.net.NoRouteToHostException
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new NoRouteToHostException();
// return false; remove return
}