我在VB.Net中打开一个TcpClient连接,我把这部分代码放在try / catch块中。但是,当IP地址不可用时,编译后的程序仍会因未处理的异常而崩溃。
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
我认为这种通用的try / catch会捕获所有异常。但是程序崩溃了这个调用堆栈:
错误:无法建立连接,因为目标计算机拒绝连接192.168.1.158:9100
堆栈追踪:
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()