Skip to content

Gendarme.Rules.Interoperability.DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule(2.10)

Sebastien Pouliot edited this page Jan 22, 2011 · 2 revisions

DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule

Assembly: Gendarme.Rules.Interoperability
Version: 2.10

Description

This rule checks for delegates which are created for methods which don't have exception handling and then passed to native code. Every delegate which is passed to native code must include an exception block which spans the entire method and has a catch all block.

Examples

Bad example:

delegate void Callback ();
[DllImport ("mylibrary.dll")]
static extern void RegisterCallback (Callback callback);
public void RegisterManagedCallback ()
{
    RegisterCallback (ManagedCallback);
}
public void ManagedCallback ()
{
    // This will cause the process to crash if native code calls this method.
    throw new NotImplementedException ();
}

Good example:

delegate void Callback ();
[DllImport ("mylibrary.dll")]
static extern void RegisterCallback (Callback callback);
public void RegisterManagedCallback ()
{
    RegisterCallback (ManagedCallback);
}
public void ManagedCallback ()
{
    try {
        throw new NotImplementedException ();
    }
    catch {
        // This way the exception won't "leak" to native code
    }
    try {
        throw new NotImplementedException ();
    }
    catch (System.Exception ex) {
        // This is also safe - the runtime will process this catch clause,
        // even if it is technically possible (by writing assemblies in managed
        // C++ or IL) to throw an exception that doesn't inherit from
        // System.Exception.
    }
}

Notes

  • This rule is available since Gendarme 2.6
Clone this wiki locally