Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`Fault` keyword in try block

While exploring an assembly in reflector I stumbled upon a fault keyword in a compiler generated class.

Do any of you know the meaning if this keyword?

C#

private bool MoveNext()
{
    bool flag;
    try
    {
        // [...]
    }
    fault
    {
        this.Dispose();
    }
    return flag;
}

vb.net

Private Function MoveNext() As Boolean 
    Dim flag As Boolean
    Try 
        ' [...]
    Fault
        Me.Dispose
    End Try
    Return flag
End Function
like image 767
Bjørn-Roger Kringsjå Avatar asked Feb 27 '14 10:02

Bjørn-Roger Kringsjå


People also ask

Can we throw error in try block?

The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.

Which code goes in the try block?

Java provides an inbuilt exceptional handling. The normal code goes into a TRY block.

What is Trycatch code?

Java try and catch The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

What if exception occurs in catch block?

Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.


1 Answers

Do any of you know the meaning if this keyword?

Yes. It's not valid C#, but in IL it's the equivalent of finally, but only if an exception has been thrown.

There's no direct correlation in C#, which is why the decompiler can't decompile it to proper C#. You could emulate it with something like:

bool success = false;
try
{
    ... stuff ...
    success = true; // This has to occur on all "normal" ways of exiting the
                    // block, including return statements.
}
finally
{
    if (!success)
    {
        Dispose();
    }
}

I mention it in my iterator block implementation details article which looks relevant to your particular example :)

like image 138
Jon Skeet Avatar answered Oct 25 '22 18:10

Jon Skeet