在try块c#中重新抛出异常

时间:2013-04-26 06:48:17

标签: c# try-catch rethrow

我在这里提出的第一个问题是英语不是很好,所以请耐心等待我,

我正在编写一个允许用户编写与'drivers'接口的脚本的应用程序,脚本和驱动程序都是独立的类库dll。这些类通过传递的回调委托进行通信,因此在编译时它们不会被链接。

  

示例:(脚本) - >(处理的程序   通信) - >(驱动程序)

现在我的问题是:

当脚本通过委托执行方法并抛出异常时,异常会冒泡回到脚本中,如果用户在try-catch块中捕获它,用户可以处理它,如果没有,则异常有被我的计划所吸引。

这样做很好,但我不知道这是否是正确的方法:

delegate object ScriptCallbackDelegate(string InstanceName, string MethodName, object[] Parameters);

static private object ScriptCallbackMethod(string InstanceName, string MethodName, object[] Parameters)
{
    try
    {
         return InterfaceWithDriver(InstanceName, MethodName, Parameters);
    }
    catch( Exception e )
    {
         try
         {
             throw;
         }
         catch
         {
             Console.WriteLine("Script did not handle exception: " + e.Message);
             return null;
         }
    }

}

2 个答案:

答案 0 :(得分:3)

catch (Exception e)
{
    try
    {
        throw;
    }
    catch
    {
        Console.WriteLine("Script did not handle exception: " + e.Message);
        return null;
    }
}

在语义上与:

相同
catch (Exception e)
{
    Console.WriteLine("Script did not handle exception: " + e.Message);
    return null;
}

脚本永远不会看到内部throw - 它被C#代码捕获。

答案 1 :(得分:1)

您的代码中导致的异常永远不会离开它,例如在下面你可以看到类似的行为。

using System;

namespace Code.Without.IDE
{
    public static class TryCatch
    {
        public static void Main(string[] args)
        {
            try
            {
                try
                {
                    throw new Exception("Ex01");
                }
                catch(Exception ex)
                {
                    try
                    {
                        throw;
                    }
                    catch
                    {
                        Console.WriteLine("Exeption did not go anywhere");
                    }
                }
                Console.WriteLine("In try block");
            }
            catch
            {
                Console.WriteLine("In catch block");
            }
        }
    }
}

生成以下输出:

  

------ C:\ abhi \ Code \ CSharp \,不带IDE \ TryCatch.exe

     

执行没有去任何地方

     

在try block中

     

------进程返回0

相关问题