如何抑制(.net)异常对象的创建? [英] How to supress the creation of an (.net) Exception object?

查看:91
本文介绍了如何抑制(.net)异常对象的创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不在乎抛出异常。我可以用某种方式编写代码来创建它吗?

If I do not care about a thrown Exception. Can I code in a way as not to create it?

换句话说,可以抛出异常,但是不会创建Exception对象?

In other words, can an Exception be thrown but no Exception object be created?

一个例子 - 使用System.Net.Sockets.Socket的简单示例

An example - Simple example using a System.Net.Sockets.Socket

 Socket acceptingSocket;
acceptingSocket.Blocking = false;

while(condition)
{
    try
    {
        Socket acceptedSocket = acceptingSocket.Accept(); //(i)
        doWork(acceptedSocket);
    }
    catch{}
}

因为套接字在非阻塞模式
如果没有连接接受
a SocketException抛出在点(i)
和条件循环继续。

because the socket is in non-blocking mode if there is no connection to accept a SocketException is thrown at point (i) and the conditional loop continues.

使用这个代码实现 - 将创建SocketException对象?

using this code implementation - will the SocketException object be created?

如果它被创建 - 有没有办法不创建它?

AND if it is created - is there a way to NOT create it?

推荐答案

你不能抑制异常,你只能忽略它们。在任何情况下,它不是创建异常对象是昂贵的 - 这是抛出异常时发生的堆栈步骤。

You can't suppress exceptions, you can only ignore them. In any case, it's not the creating of the Exception object that's expensive -- it's the stack walk that happens when the exception is thrown.

另外,

catch(SocketException) {}

不是

catch { } or catch(Exception) { }

:)

这篇关于如何抑制(.net)异常对象的创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆