Skip to main content
 首页 » 编程设计

c#之在 try block 中重新抛出异常 c#

2024年02月13日12zdz8207

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

我正在编写一个应用程序,允许用户编写与“驱动程序”交互的脚本,脚本和驱动程序都是单独的类库 dll。这些类通过传递的回调委托(delegate)进行通信,因此在编译时它们没有链接。

example: (Script)-->(The program that handles communication)-->(drivers)

现在我的问题是:

当脚本通过委托(delegate)执行方法并抛出异常时,异常会被回传给脚本,如果用户在 try-catch block 中捕获到它,则用户可以处理它,否则,异常有被困在我的程序中。

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

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; 
         } 
    } 
 
} 

请您参考如下方法:

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# 代码捕获。