如何用C#用户自定义异常? [英] How to write User Defined exceptions in C#?

查看:319
本文介绍了如何用C#用户自定义异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好任何一个可以告诉我怎么写用户定义的异常在C#中?正如我们在Java中,我们才能在C#写?

hi can any one tell me how to write user defined exceptions in C#?As we have in Java can we write in C#?

推荐答案

这实际上是因为它是Java中都是一样的 - 延长例外类。

It is practically the same as it is in Java - you extend the Exception class.

在最基本的形式

public class CustomException : System.Exception
{
  public CustomException()
  {
  }

  public CustomException(string message)
    : base(message)
  {
  }

  public CustomException(string message, System.Exception innerException)
    : base(message, innerException)
  {
  }
}

要这个,然后添加你要使用字段或属性来捕获数据。

To this, then add the data that you want to capture using either fields or properties.

出于兴趣,在回答这个问题之前,我查了自定义异常的微软设计Guildlines。 设计自定义异常(MSDN)

Out of interest, before answering this question, I checked the Microsoft Design Guildlines on Custom Exceptions. Designing Custom Exceptions (MSDN)


  1. 避免深命名空间的层次结构。

  2. 如果可能的话,从一个派生所提供的公共基础例外,即的ArgumentException 不要 ApplicationException的派生。这不是有害的,它是在这样做没有任何意义。 MSDN博客文章上ApplicationException的

  3. 使用例外后缀。

  4. 请例外序列化通过实施 ISerializable的接口。显然异常必须是序列化的跨应用程序域和远程处理边界正常工作。

  5. 在一个私人异常状态存储安全敏感信息,添加的SecurityPermission属性,以确保只有受信任的代码可以得到的信息。

  1. Avoid deep namespace hierarchies.
  2. If possible, derive from one the provided common base exceptions, i.e., ArgumentException. HOWEVER Do not derive from ApplicationException. It is not harmful, it is no point in doing so. MSDN Blog Post on ApplicationException.
  3. Use the "Exception" suffix.
  4. Make exceptions serializable by implementing the ISerializable interface. Apparently an exception must be serializable to work correctly across application domain and remoting boundaries.
  5. Store security-sensitive information in a private exception state, add a SecurityPermission attribute to ensure that only trusted code can get the information.

我的的建议你阅读的设计指南 MSDN上。

I highly recommend reading the Design Guidelines on MSDN.

这篇关于如何用C#用户自定义异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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