Question

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

}
Was it helpful?

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.

OTHER TIPS

Exception caused in your code never leaves it, e.g. in following you can see a similar behavior.

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

generates following output:

------ C:\abhi\Code\CSharp\without IDE\TryCatch.exe

Exeption did not go anywhere

In try block

------ Process returned 0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top