返回自定义异常 [英] Returning a custom exception
本文介绍了返回自定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class CustomException:Exception
{
public CustomException()
:base(){}
public CustomException(string message)
:base(message){}
public CustomException字符串格式,params对象[] 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和convert exception
throw new CustomException(Divide by Zero !!!!);
}
}
catch(CustomException ex)
{
Console.Write(Exception);
Console.ReadKey();
}
I am trying to implement my own Exception class in C#. For this purpose I have created a CustomException class derived from Exception.
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) { }
}
Then I use it
static void Main(string[] args)
{
try
{
var zero = 0;
var s = 2 / zero;
}
catch (CustomException ex)
{
Console.Write("Exception");
Console.ReadKey();
}
}
I'm expecting I will get my exception but all I get is a standard DivideByZeroException. How can I catch a divide by zero exception using my CustomException class? Thanks.
解决方案
You can't magically change type of exception thrown by existing code.
You need to throw
your exception to be able to catch it:
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();
}
这篇关于返回自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文