This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

5 Good Practices for Error Handling in C#


One of the simplest ways to stop having bugs in your program or app is to keep away from dealing with errors that might happen in your code. In case you can keep away from them, you will not need to test for them and deal with them after they occur, proper?

Whereas that sounds good in concept, it is not all the time doable to utterly forestall errors from occurring; in any other case you would not have a program or app in any respect! When an error does happen and your program cannot recuperate by itself, the way you deal with the error will depend upon how a lot data the error supplies about what brought on it and the place the issue occurred.

That’s the reason I’ve determined to elucidate 5 easy and helpful methods to deal with errors in C#.




Perceive what’s error dealing with

Initially, it’s mandatory to know what error dealing with means. The term error handling refers to a software program software’s response and restoration mechanisms within the occasion of an error. That’s to say, it’s a course of that includes precisely predicting, detecting, and resolving errors in functions, packages, or communication.

Sustaining a program’s common execution movement is made simpler by way of error dealing with. In terms of error-handling approaches, many functions actually encounter a slew of architectural points.

🧠Keep in mind: thrown errors are good.




All the time preserve hint of the exception stack

Utilizing throw e; shouldn’t be a great way to throw a caught exception since C# permits us, merely with throw;, to throw the exception in a catch block.

This fashion we might preserve observe of the stack and get a a lot better view of the exception.

Dangerous method:

strive
{
    FunctionThatMightThrow();
}
catch (Exception ex)
{
    logger.LogInfo(ex);
    throw ex;
}
Enter fullscreen mode

Exit fullscreen mode

Great way:

strive
{
    FunctionThatMightThrow();
}
catch (Exception error)
{
    logger.LogInfo(error);
    throw;
}
Enter fullscreen mode

Exit fullscreen mode

Together with data in an exception is an effective follow since it should assist in the debugging of the error. If, however, the objective is to file an exception, then throw ought to be used to go the buck to a caller.




Avoiding the usage of “throw ex”

At first look, any developer may imagine that throw ex is one of the best ways to rethrow an exception after catching it. Sure, it’s a easy technique to do it, however not the precise technique to do it. This selection shouldn’t be good since you would lose the stack hint.

Dangerous method:

strive
{
    // Do one thing..
}
catch (Exception ex)
{
    // Any motion one thing like roll-back or logging and so on.
    throw ex;
}
Enter fullscreen mode

Exit fullscreen mode

Great way:

strive
{
    // Do one thing..
}
catch (Exception ex)
{
    // Any motion one thing like roll-back or logging and so on.
    throw;
}
Enter fullscreen mode

Exit fullscreen mode

We will see within the good technique to do it I’ve merely used throw. On this method, the unique exception stack could be conserved. In any other case, with throw ex, it could be overwritten with the road of code the place this assertion was referred to as.




Keep away from utilizing if circumstances

It’s best to think about using quite a few catch blocks for exception dealing with if you’ll want to do completely different actions relying on the type of exception. A foul follow is to make use of if conditional. 

Dangerous method:

strive
{
    // Do one thing..
}
catch (Exception ex)
{
    if (ex is TaskSchedulerException)
    {
        // Take motion
    }
    else if (ex is TaskCanceledException)
    {
        // Take motion
    }
}
Enter fullscreen mode

Exit fullscreen mode

Great way:

strive
{
    // Do one thing..
}
catch (TaskCanceledException ex)
{
    // Take motion 
}
catch (TaskSchedulerException ex)
{
    // Take motion
}
Enter fullscreen mode

Exit fullscreen mode

Even when we’re creating quite a few catch blocks, it’s all the time recommended to create a catch block that features the Exception argument as the ultimate catch block. It supplies as an auxiliary catch block.




All the time analyze the caught errors

In case you catch an error, there is no level in ignoring it and letting it go since you will not have an opportunity to repair it or do something about it.

It’s all the time higher, if you realize an error may happen, to wrap that code in a strive/catch.

Dangerous method:

strive
{
    FunctionThatMightThrow();
}
catch (Exception ex)
{
    // silent exception
}
Enter fullscreen mode

Exit fullscreen mode

Great way:

strive
{
    FunctionThatMightThrow();
}
catch (Exception error)
{
    NotifyUserOfError(error);
    // Another choice
    ReportErrorToService(error);
}
Enter fullscreen mode

Exit fullscreen mode

As we will see, throwing the error shouldn’t be an awesome resolution as a result of it’d get misplaced within the console amongst all of the printed stuff. By wrapping it in a strive/catch, we will later (in case an error happens there) create a plan or have a code path on methods to deal with it.


The following pointers are tailored from Clean Code Javascript. Thanks Ryan McDermott to your nice contribution!

From Dotnetsafer we need to thanks to your time in studying this text and remember that in our .NET Blog you possibly can be taught extra.

And keep in mind: Now you possibly can strive without spending a dime our .NET obfuscator. It’s also possible to shield your functions straight from Visible Studio with the [.NET Obfuscator for Visual Studio]

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?