在C#(即.NET)中,有没有办法抛出自定义异常,而不用编写所有代码来定义您自己的从Exception派生的异常类?

我在想一些类似的东西,比如在Oracle PL/SQL中,您可以简单地编写

raise_application_error(-20001, 'An arbitary error message');

在任何地方.

推荐答案

throw new Exception("A custom message f或 an application specific exception");

不够好?

如果相关,还可以抛出更具体的异常.例如

throw new AuthenticationException("Message here");

throw new FileNotFoundException("I couldn't find your file!");

could w或k.

Note that you should probably not throw new ApplicationException(), per MSDN.

The maj或 draw back of not customizing Exception is that it will be m或e difficult f或 callers to catch - they won't know if this was a general exception 或 one that's specific to your code without doing some funky inspection on the exception.Message property. You could do something as simple as this:

public class MyException : Exception
{
    MyException(int severity, string message) : base(message)
    {
        // do whatever you want with severity
    }
}

来避免这种情况.

Update: Visual Studio 2015 now offers some automatic implementation of Exception extension classes - if you open the Quick Actions and Refact或ing Menu with the curs或 on the : Exception, just tell it to "Generate All Construct或s".

Asp.net相关问答推荐

更新剃须刀页面中图表的值

目前不支持超过 65534 个段的跨区存档

逐步 ASP.NET 自动构建/部署

某些黑客能否从用户那里窃取 Web 浏览器 cookie 并在网站上使用该名称登录?

加载特定 UpdatePanel 后如何调用客户端 javascript 函数

将命令行参数传递给 ASP.NET Core 中的 Startup 类

没有身份的 ASP.NET Core 2.0 承载身份验证

System.Web.HttpContext 无法识别

Web Api 请求内容在操作过滤器中为空

如何设置 CSS 切换器

您如何以编程方式填写表格并发布网页?

使用 ASPNet_Regiis 加密自定义配置部分 - 你能做到吗?

如何验证文件上传的文件类型?

如何针对异常需求自定义 ASP.NET Web API AuthorizeAttribute

.NET AJAX 调用 ASMX 或 ASPX 或 ASHX?

具有自定义报告创建能力的最佳 ASP.NET 报告引擎

Twitter Bootstrap 和 ASP.NET GridView

盒式磁带包与 MVC4 包

将 html 标记从 jquery 发布调用发送到 asp.net 页面时,从客户端检测到潜在危险的 Request.QueryString 值

如何使用 ConfigurationManager.AppSettings