如何将错误发送到Exception类的构造函数,除了字符串?

huangapple go评论41阅读模式
英文:

How do I send an error to the constructor of the Exception class in addition to string?

问题

我试图将异常发送到基本构造函数,但我不知道如何发送它。
我需要创建一个异常吗?
这是类的代码:

public class InvalidEntityException : Exception
{
public InvalidEntityException(string message, Exception ex) : base(message, ex) { }
}

异常看起来像这样:

> throw new InvalidEntityException( "Add function :: DAL", ???????);

我应该如何抛出异常?
英文:

I am trying send exceptions to the base constructor but I don't know how to send it.
Should I need create an exception?
Here the code of the class:

public class InvalidEntityException : Exception
{
    public InvalidEntityException(string message, Exception ex) : base(message, ex) { }
}

The exception look like this:

> throw new InvalidEntityException( "Add function :: DAL", ???????);

How do I need throw the exceptions?

答案1

得分: 1

以下是翻译好的内容:

如果你在一个catch子句内或者有一个当前的异常对象可用,那么请使用该异常对象。

try
{
    // 代码
}
catch (Exception ex)
{
    throw new InvalidEntityException("Add function :: DAL", ex);
}

如果你没有当前的异常对象,只需传递null

throw new InvalidEntityException("Add function :: DAL", null);

来自Exception类构造函数的文档

public Exception (string? message, Exception? innerException);

innerException 异常

作为当前异常的原因的异常,或者如果未指定内部异常,则为null引用(在Visual Basic中为Nothing)。

英文:

If you are inside a catch clause or have a current exception object available otherwise, use that exception object.

try
{
    // code
}
catch(Exception ex)
{
    throw new InvalidEntityException("Add function :: DAL", ex);
}

If you don't have a current exception object, just pass null.

throw new InvalidEntityException("Add function :: DAL", null);

From the documentation of the Exception class constructor:

> public Exception (string? message, Exception? innerException);
>
> innerException Exception
>
> The exception that is the cause of the current exception, or a null
> reference (Nothing in Visual Basic) if no inner exception is
> specified.

huangapple
  • 本文由 发表于 2023年2月19日 22:07:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定