Best Practices for Exception Handling in C #

As part of the imminent start of the "C # Developer. Professional" course, we have prepared a translation of the material for you. We also invite everyone to a free demo lesson "DI containers for C #" . In this lesson we: 1) Understand what the DI principle is and why it is needed; 2) Learn to apply DI without using containers; 3) Let's consider two popular DI-containers for C #: Windsor and Autofac, let's analyze their pros and cons; 4) We will learn how to register dependencies, manage their life cycle, apply dependency injection.


















. - ( , ). C#.





. , ยซ ยป . . , try/catch



:





try
{
    try
    {
        //  - ,     SpecificException

    }
    catch (SpecificException specificException)
    {
        log.LogError(specificException, "Specific error");
    }
    

    //  - 
}
catch (Exception exception)
{
    log.LogError(exception, "General erro");
}
      
      



, , , try/catch



, . SpecificException



catch



, . :





catch (SpecificException specificException)
{
    // ...
    throw specificException;
}
      
      



:





catch (SpecificException specificException)
{
    // ...
    throw;
}
      
      



, SpecificException



, , . .





. Exception, Data. . , , . elmah.io



Data Data.





Data /:





var exception = new Exception("En error happened");
exception.Data.Add("user", Thread.CurrentPrincipal.Identity.Name);
throw exception;
      
      



user



, .





, . try/catch



:





try
{
    service.SomeCall();
}
catch (Exception e)
{
    e.Data.Add("user", Thread.CurrentPrincipal.Identity.Name);
    throw;
}
      
      



, SomeCall



, . throw



catch



.





, - , :





try
{
    File.WriteAllText(path, contents);
}
catch (Exception e)
{
    logger.Error(e);
}
      
      



Exception



. , .NET, , . โ€” , .





, :





try
{
    File.WriteAllText(path, contents);
}
catch (ArgumentException ae)
{
    Message.Show("Invalid path");
}
catch (DirectoryNotFoundException dnfe)
{
    Message.Show("Directory not found");
}
catch (Exception e)
{
    var supportId = Guid.NewGuid();
    e.Data.Add("Support id", supportId);
    logger.Error(e);
    Message.Show($"Please contact support with id: {supportId}");
}
      
      



ArgumentException



DirectoryNotFoundException



Exception



, . , . Exception



support id



, ( , ) .





, , , , โ€” . :





, . , , .





โ€” NullReferenceException



. null



, null



. , NullReferenceException



:





Address a = null;
var city = a.City;
      
      



a . , , a .





city



, , null-condition



:





Address a = null;
var city = a?.City;
      
      



?



a C# , null



. city



null



.





โ€” . FormatException



:





var i = int.Parse("invalid");
      
      



invalid



. try/catch



, int



, , , 1000 :





if (int.TryParse("invalid", out int i))
{
}
      
      



, invalid



int



, TryParse



true



i



. .





, Java- ( .NET -). . , - Java, .NET C#. , , . , , Data:





public class MyVerySpecializedException : Exception
{
    public MyVerySpecializedException() : base() {}
    public MyVerySpecializedException(string message) : base(message) {}
    public MyVerySpecializedException(string message, Exception inner) : base(message, inner) {}
    
    public int Status { get; set; }
}
      
      



MyVerySpecializedException



(, , :D) , . , Status . :





try
{
    service.SomeCall();
}
catch (MyVerySpecializedException e) when (e.Status == 500)
{
    // Do something specific for Status 500
}
catch (MyVerySpecializedException ex)
{
    // Do something general
}
      
      



when



, MyVerySpecializedException



, Status 500. catch MyVerySpecializedException



.





. :





try
{
    service.SomeCall();
}
catch
{
    // 
}
      
      



, โ€” , . , , , . .





, NLog Serilog. - ASP.NET (Core), elmah.io .






"C# Developer. Professional".





ยซDI- C#ยป.








All Articles