简体   繁体   English

我有一个由于某种原因没有被捕获的ConnectException

[英]I have a ConnectException that isn't being caught for some reason

I'm working on an Android application that uses sockets. 我正在使用套接字的Android应用程序上工作。 I have a function called initializeStreams() which opens the socket and attempts a connection. 我有一个名为initializeStreams()的函数,它将打开套接字并尝试连接。 This function throws a ConnectException if the connection could not be established. 如果无法建立连接,此函数将引发ConnectException。 But for some reason, in the code that calls initializeStreams(), which has a catch block for ConnectException, the log prints out its own stack trace for the exception instead of going to the catch block. 但是由于某种原因,在调用initializeStreams()的代码中,该代码具有ConnectException的catch块,日志将打印出自己的异常堆栈跟踪信息,而不是转到catch块。 The catch block is never reached at all, even though the exact exception is being thrown. 即使抛出了确切的异常,也根本不会到达catch块。 Here's the code: 这是代码:

The try block: 尝试块:

try {
        initializeStreams();

            /* other code */

    } catch (ConnectException e) {
        Log.i(TAG, "caught connect exception");

    }

initializeStreams(): initializeStreams():

    public void initializeStreams() throws ConnectException {
    try {
        Log.i(TAG, "Attempting to connect");

        requestSocket = new Socket(SERVER_ADDR, PORT);

                    /* other code */


    } catch (IOException e) {
        e.printStackTrace();
    }

I can't figure this out, so any help would be much appreciated. 我无法弄清楚,因此将不胜感激。

You need to chain your Exception throwing it in the catch block. 您需要链接您的Exception,将其扔到catch块中。 Try the following: 请尝试以下操作:

public void initializeStreams() throws ConnectException {
try {
    Log.i(TAG, "Attempting to connect");

    requestSocket = new Socket(SERVER_ADDR, PORT);

                /* other code */


} catch(ConnectException e){
    throw e;
}

catch (IOException e) {
    e.printStackTrace();
}

ConnectException extends SocketException which in turn extends IOException, so the catch for IOException in initializeStreams() catches the ConnectException. ConnectException扩展了SocketException ,后者又扩展了IOException,因此initializeStreams()IOException捕获将捕获ConnectException. I would just remove that try/catch block altogether: there's not much point in returning cleanly from this method without a connection. 我将完全删除try/catch块:没有连接时从此方法干净地返回没有什么意义。

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

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