我想请你在下面的代码中解释异常系统是如何工作的:
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()吗?
@EDIT:
里面的代码很复杂,需要几页。我可以告诉你,我在内部进行了多次异步操作,比如下载文件,接收数据包等。换句话说,还有其他线程在循环中创建。
@ 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);
}
答案 0 :(得分:1)
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();
}
答案 1 :(得分:0)
我能想到为什么会出现这种行为的唯一原因是你在try块中开始新的线程。因此,如果您正在启动任何新线程或使用任务parallell库或plinq,您可能会得到类似的东西。
但检查 - 调试被注释替换的代码真的很难......