Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better alternative to Try Catch madness?

Tags:

c#

Is there a better alternative to the try catch madness in the code below? I'm collecting all kinds of similar system information and have several more of these annoying try catch constructions and would very much like to get rid of them.

Note that this actually makes sense. Not all the process information in the try blocks can get retrieved, and what's not available is just optional anyway, while at the same time it's not acceptable to skip what is available, hence why there isn't just one try catch pair.

If only those try catch statements could go into the Append() method.

foreach (Process proc in Process.GetProcesses())
{
    try { Append(proc.Threads.Count); } catch { }
    try { Append(proc.Id); } catch { }
    try { Append(proc.ProcessName); } catch { }
    try { Append(proc.BasePriority); } catch { }
    try { Append(proc.StartTime); } catch { }

    Append(proc.HandleCount,
        proc.PrivateMemorySize64,
        proc.NonpagedSystemMemorySize64,
        proc.PagedMemorySize64,
        proc.PeakPagedMemorySize64,
        proc.PeakVirtualMemorySize64);
}
like image 434
Thorham Avatar asked Jul 04 '19 14:07

Thorham


1 Answers

In my opinion, your approach in general is wrong, but it will work. You can 'optimize' this in readability by using a method:

private void AppendSafe<T>(Func<T> f)
{
    T val;

    try
    {
        val = f();
    }
    catch { return; }

    Append(val);
}

AppendSafe(() => proc.Threads.Count);
AppendSafe(() => proc.Id);
AppendSafe(() => proc.ProcessName);
AppendSafe(() => proc.BasePriority);
AppendSafe(() => proc.StartTime);

But I would argue to catch relevant exceptions. You don't want a NullReferenceException to go unnoticed.

Also, since exceptions are expensive, it is better to work out which properties are available on what platforms and test for that. At least you will minimize performance impact when calling this frequently.

like image 141
Patrick Hofman Avatar answered Nov 13 '22 18:11

Patrick Hofman