user3223507 user3223507 - 3 months ago 8
C# Question

Catching an exception

I'm currently getting an exception thrown and the message it gives is Value does not fall within the expected range. I'm trying to right a piece of code to grab this exception and suppress it - I know what the issue is - essentially someone is trying to pull a record from a list using an id which doesn't exist.

Any ideas how i go about catching this?

Answer

To suppress an exception you need to do something like this

try
{
     // Code that may throw an exception.
}
catch (Exception ex) // Better to use a more specific exception class
{
    // Do nothing - That suppresses the exception.

    // If you want to do additional checking that may continue the exception
    // up the stack use "throw" on its own - which compiled to CIL/MSIL's
    // "rethrow" and doesn't drop much of the information that would
    // go if you did "throw ex"
}

That's all there is to suppressing an exception.

For the sanity of those that have to maintain this code (or yourself in 6 months time when you've forgotten the specifics of why you did this), it would also be good to comment exactly why you are suppressing the exception. If I see code that suppresses an exception I always want to know why.