0
我想从catch块中抛出一个自定义的异常,也就是说,每当发生任何异常时它都应该被catch块捕获并抛出一个自定义的异常。我正在尝试使用下面的代码,但将catch块中的运行时异常设置为“未处理的异常”。我们可以从catch块中抛出一个自定义异常吗?
try{
///some error
}
catch(Exception e){
try{
throw new CustomException("Exception1", e);
}
catch(CustomException ce)
{
Console.WriteLine("Custom Exception Caught" + ce.StackTrace);
}
}
public class CustomException : Exception
{
public CustomException : base()
{
}
public CustomException(string message, Exception innerException) : base(message, innerException)
{
processError(message, innerException);
}
}
public static void processError(string mgs, Exception e)
{
switch(mgs)
{
case "Exception1":
Console.WriteLine("Exception1 caught" + e.StackTrace);
break;
case "Exception2":
Console.WriteLine("Exception2 caught" + e.StackTrace);
break;
default:
Console.WriteLine("Some other Exception caught" + e.StackTrace);
break;
}
}
任何有关上述问题的提示都非常感谢。提前致谢。
“但是出现错误”对我们来说太过模糊以至于无法帮助您。你什么时候得到错误 - 在编译时或执行时?如果是在执行时,这可能是因为没有什么能够捕捉到你抛出的'CustomException' ... –
@ Jin Skeet,根据你的疑问编辑。 – Anand
你的编辑显示如果在'try'块中抛出'CustomException',但是你从下面的'catch'块抛出它......这个新异常不会被catch块捕获它上面。目前还不清楚你想在这里发生什么 - 你想要抛出'CustomException'吗? –