emert117
emert117

Reputation: 1488

Best practice for many try-catch blocks

I have many statements that can throw exceptions. Exceptions are not important.

My system accepts missing patient data fields.

patientData.PatientId = message.Find(...);
try
{
    patientData.Gender = message.Find(...);
}
catch
{
    // no gender, no problem
}

try
{
    patientData.DateOfBirth = message.Find(...);
}
catch 
{
    // no DateOfBirth, no problem
}
// and many other try-catch blocks ...

What is the best way to write these statements that can throw exceptions but not critical?

Upvotes: 0

Views: 84

Answers (2)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

In your example, you can create static TryFindMessage method in addition to Find. In case of exception just return false. For example: bool Message.TryFind(..., Message message, out string result).

But, if you wish some generic approach which you can use with anything, then you can take advantage of delegates and create some static helper.

You can use Action or Func in that case. Add another extension method which accepts Func if you need to return some value from executed function.

 public static class SilentRunner
    {
        public static void Run(Action action, Action<Exception> onErrorHandler)
        {
            try
            {
                action();
            }
            catch (Exception e)
            {
                onErrorHandler(e);
            }
        }

        public static T Run<T>(Func<T> func, Action<Exception> onErrorHandler)
        {
            try
            {
                return func();
            }
            catch (Exception e)
            {
                onErrorHandler(e);
            }

            return default(T);
        }
    }

And then use it so:

SilentRunner.Run(
     () => DoSomething(someObject),
     ex => DoSomethingElse(someObject, ex));

In case of Func, you can take result as well:

var result = SilentRunner.Run(
     () => DoSomething(someObject),
     ex => DoSomethingElse(someObject, ex));

Upvotes: 2

Fabio
Fabio

Reputation: 32445

I have many statements that can throw exceptions. Exceptions are not important.

This can be dangerous, because exceptions can be thrown for different reasons, not only because of missing property.

I would advise instead of swallowing exception, modify code to return default value(null) when value is not found.

You can introduce new method in message class, for example FindOrDefault

// Pseudo code
public T FindOrDefault(string property)
{
     return CanFind(property) ? Find(property) : default(T);
}

Usage of such method will be self explanatory

patientData.PatientId = message.Find(...); // Mandatory - must throw if not found
patientData.Gender = message.FindOrDefault(...);
patientData.DateOfBirth = message.FindOrDefault(...);

Upvotes: 1

Related Questions