我试图在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) { }
}
Run Code Online (Sandbox Code Playgroud)
然后我用它
static void Main(string[] args)
{
try
{
var zero = 0;
var s = 2 / zero;
}
catch (CustomException ex)
{
Console.Write("Exception");
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
我期待我会得到我的例外,但我得到的只是标准的DivideByZeroException.如何使用CustomException类捕获除零异常?谢谢.
Ale*_*kov 29
您不能神奇地更改现有代码抛出的异常类型.
您需要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();
}
Run Code Online (Sandbox Code Playgroud)
Dzm*_*voi 17
首先,如果你想看到自己的异常,你应该throw
在代码中的某个地方:
public static int DivideBy(this int x, int y)
{
if (y == 0)
{
throw new CustomException("divide by zero");
}
return x/y;
}
Run Code Online (Sandbox Code Playgroud)
然后:
int a = 5;
int b = 0;
try
{
a.DivideBy(b);
}
catch(CustomException)
{
//....
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
58589 次 |
最近记录: |