返回自定义异常
本文关键字:自定义异常 返回 | 更新日期: 2023-09-27 18:09:07
我正在尝试在c#中实现我自己的Exception类。为此,我创建了一个从Exception派生的CustomException类。
class CustomException : Exception
{
public CustomException()
: base() { }
public CustomException(string message)
: base(message) { }
public CustomException(string format, params object[] args)
: base(string.Format(format, args)) { }
public CustomException(string message, Exception innerException)
: base(message, innerException) { }
public CustomException(string format, Exception innerException, params object[] args)
: base(string.Format(format, args), innerException) { }
}
然后使用
static void Main(string[] args)
{
try
{
var zero = 0;
var s = 2 / zero;
}
catch (CustomException ex)
{
Console.Write("Exception");
Console.ReadKey();
}
}
我期待我会得到我的异常,但我得到的只是一个标准的DivideByZeroException。我如何使用我的CustomException类捕获除零异常?谢谢。
您不能神奇地改变现有代码抛出的异常类型。
你需要throw
你的异常能够捕获它:
try
{
try
{
var zero = 0;
var s = 2 / zero;
}
catch (DivideByZeroException ex)
{
// catch and convert exception
throw new CustomException("Divide by Zero!!!!");
}
}
catch (CustomException ex)
{
Console.Write("Exception");
Console.ReadKey();
}
首先,如果你想看到你自己的异常,你应该在代码的某个地方throw
它:
public static int DivideBy(this int x, int y)
{
if (y == 0)
{
throw new CustomException("divide by zero");
}
return x/y;
}
:
int a = 5;
int b = 0;
try
{
a.DivideBy(b);
}
catch(CustomException)
{
//....
}