[英]Catching multiple exceptions in console app using one try{…}catch{…} block
我想請您向我解釋以下代碼段中異常系統的工作方式:
static void Main(string[] args)
{
try
{
//Code which throws exceptions from time to time and runs in a loop
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
我注意到令我驚訝的事情。 當引發異常時,try {...}塊中的代碼仍在運行,並且可能引發更多異常,這些異常將被打印到控制台窗口。 循環中的代碼是否應該完成其執行並最后“跳轉”到Console.ReadKey()?
@編輯:
里面的代碼很復雜,需要花費幾頁。 我可以告訴你,我在內部進行了多個異步操作,例如下載文件,接收數據包等。換句話說,在循環中創建了其他線程。
@ EDIT2:大概這是負責該行為的代碼:
public SomeConstructor(Socket server)
{
_pb = new PacketBuilder(server, c);
SocketWrapper sw = new SocketWrapper(server, Globals.recvBufferSize);
sw.Socket.BeginReceive(sw.Buffer, 0, Globals.recvBufferSize, SocketFlags.None,PacketReceiveCallback, sw);
_pi = new PacketInterpreter(this, c);
}
private void PacketReceiveCallback(IAsyncResult iar)
{
SocketWrapper sw = iar.AsyncState as SocketWrapper;
int bytesReceived = sw.Socket.EndReceive(iar);
_pi.Interpret(sw.Buffer, 0, bytesReceived);
if (bytesReceived > 0)
sw.Socket.BeginReceive(sw.Buffer, 0, Globals.recvBufferSize, SocketFlags.None, PacketReceiveCallback, sw);
}
只要不引發異常,try塊中的代碼就會執行。 如果在try塊中引發異常,則以下代碼將不會執行,並且將跳轉到catch塊。
static void Main(string[] args)
{
try
{
//Code which throws exceptions from time to time and runs in a loop
Console.WriteLine("Line 1");
throw new Exception("Sample Exception"); // your code will stop here and following line will not prine.
Console.WriteLine("This line will not print");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
我能想到為什么會出現這種行為的唯一原因是,如果要在try塊中啟動新線程。 因此,如果您要啟動任何新線程或使用任務並行庫或plinq,則可能會得到類似的信息。
但是,實際上很難對由注釋代替的代碼進行調試-調試...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.