2013-05-18 85 views
0

如果我放了一個無意義的URL,不會引發任何異常,並且我的代碼的其餘部分都不會執行,甚至連調用連接的方法的其餘部分都不會執行。Socket.connect不會在Android中拋出異常

try { 
     socketCliente.connect(new InetSocketAddress("f", port), 2000); 

    } catch (UnknownHostException e) { 
     getError("Host doesn't exist"); 
     return -1; 
    } catch (IOException e) { 
     getError("Could not connect: The host is down"); 
     return -1; 
    } 
+0

你有互聯網許可?此代碼是否在UI THread上運行? – Blackbelt

+0

嘗試捕獲一般異常而不是IO和UnknownHost異常?我預見你可能會得到malform的URL而不是你正在捕捉的2。 –

+0

@ChorWaiChun儘管OP說了什麼,在這段代碼中沒有URL。 – EJP

回答

0

添加另一個catch語句。

catch (Exception e) { 
    Log.d(TAG, e.getMessage(),e); 
    Toast.makeText(getApplicationContext(), "Unexpected Error:" + e.getMessage(), Toast.LENGTH_LONG).show(); 
} 

這會寫入日誌並彈出敬酒告訴你發生了什麼事。

+0

沒有任何異常被執行後,連接線沒有其他任何執行。 – MarkHolland

+1

它可能試圖連接。它最終會超時。 –

0

這很奇怪,你可以再添加兩行,如下所示,看看你得到了什麼。

另外,在日誌中,請注意這兩行之間的時間差異。

try { 
    Log.w("SOCKET", "Trying to connect..."); 
    socketCliente.connect(new InetSocketAddress("f", port), 2000); 
    Log.w("SOCKET", "Connected. No exception"); 

} catch (UnknownHostException e) { 
    getError("Host doesn't exist"); 
    return -1; 
} catch (IOException e) { 
    getError("Could not connect: The host is down"); 
    return -1; 
}