Search code examples
c#try-catchrethrow

Rethrow an exception in a try block c#


My first question here and I am not that great at english so please bear with me,

I am writing an application that allows users to write scripts that interface with 'drivers', the scripts and drivers are all separate class library dll's. These classes communicate through callback delegates that are passed , so at compile-time they are not linked.

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

Now my question is:

When a script executes a method via a delegate and it throws an exception, the exception is bubbled back up to the script and the user can handle it if they catch it in a try-catch block, if not, the exception has to be caught inside my program.

It works fine like this, but I do not know if this is the right way to go:

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

}

Solution

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

    is semantically identical to:

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

    The script is never seeing that inner throw - it is being caught by your C# code.