Exception Handling in C#: Essential Tips
Sahil Arora
Full Stack Engineer | Ex-UHG || AWS | .NET Core | Restful Web API's | C# | Angular | JavaScript | SQL Server | Snowflake | Azure DevOps | Agile (Scrum)
As developers, writing robust code is rather essential than important and a fine grained exception handling is one good way to it. It not only allows you to handle errors in the code gracefully but also provides mechanism for troubleshooting in case something goes wrong, and trust me that will definitely happen.
No code is perfect, it is our effort to take it to the zenith of perfection.
Having said that let's discuss some important concepts around exception handling in C#.
try
{
// Specific file operation
}
catch (FileNotFoundException ex)
{
logger.Error($"File not found: {ex.Message}");
}
catch (UnauthorizedAccessException ex)
{
logger.Error($"Access denied: {ex.Message}");
}
catch (Exception ex)
{
logger.Error(ex, "An unexpected error occurred.");
}
app.UseExceptionHandler("/Error");
What exception handling practices have you found most effective in your C# projects? Let's discuss in the comments!
#csharp #dotnet #exceptionhandling #codequality #softwaredeveopment #aspnetcore
Senior Software Engineer at Commonwealth Bank of Australia
1 个月Good article for beginners, but I would like to see little bit more approach using a Custom exception filter (if type of exception is unknown). If you like to cover that up too it will be great ??