gpt4 book ai didi

.net - 如何更改异常对象的异常消息?

转载 作者:行者123 更新时间:2023-12-03 10:20:42 26 4
gpt4 key购买 nike

我该如何更改 Message C# 中的异常对象?

奖金喋喋不休
Message Exception 的属性(property)是只读的:

public virtual string Message { get; }

补充阅读

同样的问题,在 PHP 中,有人回答,“你不能”,但给出了一个解决方法:

You can however determine it's class name and code, and throw a new one, of the same class, with same code, but with different message.



我如何确定异常的类名,并在 C# 中抛出一个新的同一个类,但具有不同的消息?

例如。:
catch (Exception e)
{
Exception e2 = Activator.CreateInstance(e.GetType());
throw e2;
}

不起作用,因为 Message异常的属性是只读和 .NET。请参阅原始问题。

更新

我 try catch 我期望的每种类型的异常:
try
{
reader.Read();
}
catch (OleDbException e)
{
throw new OleDbException(e, sql);
}
catch (SqlException e)
{
throw new SqlException (e, sql);
}
catch (IBM.DbException e)
{
throw new IBM.DbException(e, sql);
}
catch (OdbcException e)
{
throw new OdbcException (e, sql);
}
catch (OracleException e)
{
throw new OracleException (e, sql);
}

除了现在我的代码强制依赖于不会出现在每个解决方案中的程序集。

此外,现在异常似乎来自我的代码,而不是抛出它的行;我丢失了异常的位置信息

最佳答案

您新建了 Exception (或 - 更好 - 特定子类型)具有新消息(并将原始异常作为 InnerException 传递)。

例如。

throw new MyExceptionType("Some interesting message", originalException);

注意。如果你真的想用 Activator.CreateInstance 您可以使用可以传递参数的重载,但不能依赖不同的 Exception 派生类型来为 (message, innerException) 提供构造函数重载.

关于.net - 如何更改异常对象的异常消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9334182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com