dimanche 10 mai 2015

try block does not catch TcpClient connect exception

I'm opening a TcpClient connection in VB.Net and I have put theat part of the code in a try/catch block. But still the compiled program crashed with an unhandled exception when the IP-Address wasn't available.

Try
    ' Open connection 
    Dim client As System.Net.Sockets.TcpClient = New System.Net.Sockets.TcpClient
    client.Connect(Printer.IpAddress, Printer.Port)
    ' Write ZPL String to connection 
    Dim writer As System.IO.StreamWriter = New System.IO.StreamWriter(client.GetStream(), System.Text.Encoding.GetEncoding(1252))
    writer.Write(EtikettText)
    writer.Flush()
    ' Close Connection 
    writer.Close()
    client.Close()
Catch ex As Exception
    MsgBox(ex.Message, MsgBoxStyle.OkOnly Or MsgBoxStyle.Critical, "Druckerfehler")
    lastex = ex
    Return False
End Try

I thought this kind of general try/catch would catch all exceptions. However the program crashed with this call stack:

Error: No connection could be established because the target computer refused the connection 192.168.1.158:9100

Stack trace:

at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
at System.Net.Sockets.TcpClient.Connect(IPAddress address, Int32 port)
at Cocos.ChargenEtikett.Print()

Aucun commentaire:

Enregistrer un commentaire