Showing posts with label Exception Handling. Show all posts
Showing posts with label Exception Handling. Show all posts

Tuesday, 19 April 2022

Exception Handling Techniques & Tricks C#

 Exception handling could turn to costly operation in your code if you don’t pay much attention to it.

  1. Use Catch only if needed as it is costly operation, if possible use if instead.
    i.e. Divide by zero exception. why not do a check for zero before divide operation if possible.
try
{
var result = myVal/someParam;
}
catch(DivideByZeroException ex)
{
//do what you want
}
above code can be refactored like below to avoid the costly catch operation.if(someParam != 0)
{
var result = myVal/someParam;
}
else
{
//do what you wanted to do in the catch block
}
try
{
//code
}
catch(Exception)
{
}
return something;
try
{
//code
}
catch(Exception ex)
{
throw ex;
}
return something;
ORtry
{
//code
}
catch(Exception)
{
throw;
}
return something;
//Bad Code
try
{
//code
}
catch(Exception ex)
{
//do something
throw ex;
}
return something;
//better Code
try
{
//code
}
catch(Exception ex)
{
//do something
throw;
}
return something;
//Bad code
try
{
//some code
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
throw ex;
}
try //inner try catch 2
{
//some code
}
catch(Exception ex)
{
throw;
}
}
catch(Exception ex)
{
//code to handle the exception
}
{
method1();
method2();
}
private void method1()
{
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
//Handle exception and do not throw back to caller.
}
}
private void method2()
{
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
//Handle exception and do not throw back to caller.
}
}
try
{
method1();
method2();
}
catch(NullException ex)
{
//Handle exception. If needed catch can be classified well based on the exception type behavior of method1 and method 2.
}
catch(Exception ex)
{
//Handle exception
}
private void method1()
{
//code
}
private void method2()
{
//code
}
{
var result = method1();
method2();
}
private int method1()
{
int result;
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
//Handle exception and do not throw back to caller.
}
finally
{
result = 0;
}
return result;
}
private void method2()
{
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
//Handle exception and do not throw back to caller.
}
finally
{
//clean your mess-ups, like closing the open connection, fallback mechanism etc.
}
}
//Bad Practice
public Result PerformAction()
{
try
{
}
catch(Exception ex)
{
throw;
}
}
//Good Practice
public Result PerformAction()
{
try
{
}
catch(Exception ex)
{
return new CustomException("An internal error occured");
}
}
public class CustomException : Exception
{
}

Wednesday, 6 April 2022

Exception Handling Techniques & Tricks C#

 Exception handling could turn to costly operation in your code if you don’t pay much attention to it.

try
{
var result = myVal/someParam;
}
catch(DivideByZeroException ex)
{
//do what you want
}
above code can be refactored like below to avoid the costly catch operation.if(someParam != 0)
{
var result = myVal/someParam;
}
else
{
//do what you wanted to do in the catch block
}
try
{
//code
}
catch(Exception)
{
}
return something;
try
{
//code
}
catch(Exception ex)
{
throw ex;
}
return something;
ORtry
{
//code
}
catch(Exception)
{
throw;
}
return something;
//Bad Code
try
{
//code
}
catch(Exception ex)
{
//do something
throw ex;
}
return something;
//better Code
try
{
//code
}
catch(Exception ex)
{
//do something
throw;
}
return something;
//Bad code
try
{
//some code
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
throw ex;
}
try //inner try catch 2
{
//some code
}
catch(Exception ex)
{
throw;
}
}
catch(Exception ex)
{
//code to handle the exception
}
{
method1();
method2();
}
private void method1()
{
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
//Handle exception and do not throw back to caller.
}
}
private void method2()
{
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
//Handle exception and do not throw back to caller.
}
}
try
{
method1();
method2();
}
catch(NullException ex)
{
//Handle exception. If needed catch can be classified well based on the exception type behavior of method1 and method 2.
}
catch(Exception ex)
{
//Handle exception
}
private void method1()
{
//code
}
private void method2()
{
//code
}
{
var result = method1();
method2();
}
private int method1()
{
int result;
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
//Handle exception and do not throw back to caller.
}
finally
{
result = 0;
}
return result;
}
private void method2()
{
try //inner try catch 1
{
//some code
}
catch(Exception ex)
{
//Handle exception and do not throw back to caller.
}
finally
{
//clean your mess-ups, like closing the open connection, fallback mechanism etc.
}
}
//Bad Practice
public Result PerformAction()
{
try
{
}
catch(Exception ex)
{
throw;
}
}
//Good Practice
public Result PerformAction()
{
try
{
}
catch(Exception ex)
{
return new CustomException("An internal error occured");
}
}
public class CustomException : Exception
{
}

Monday, 15 June 2015

Exception Handling - Best Practices

Exception Handling: A well known Concept. I hope everyone knows about it. A very simple but crucial piece of code.
In C#, it's all about try, catch and finally block.
try
{
       //Contains code which could throw unexpected error at run time which is called exception.
}
Catch(Exception)
{
      //Contains  exception handle logic, Ex.: logging.
}
finally
{
      //Contains code which will get executed if try block is executed. It will get executed if there is no exception or even if there is exception. Ex.: used to do memory release, connection close etc.
}


Looks very simple but still programmers do mistakes. So here I am going to discuss few best practices which I learned from my past experience.



1. Throwing exceptions hit performance badly. So try to minimize the 'throw' as much as possible.
Ex.:
void Method()
{
          for(int i = 0; i < 10000; i++)
          {
                try
                {  
                     if( i/2 == 0)
                            throw new Exception();
                 }
                 catch {}
         }
          Console.WriteLine("Loop Ends");
}

Above code practice is totally wrong. Just commenting out the " throw new Exception()" line of code can show the bad impact of having this line.

2. Can we put entire piece of code for a method in a single try block.
Yes. No harm in this.
Ex:
void Method()
{
       try
       {
              //Code
       }
       Catch(Exception)
       {
             
       }
}

3. Don't catch exception if you are not doing anything with the exception. Let the Calling method to catch exception and decide what to do.
Ex:
void Method()
{
       try
       {
              //Code
       }
       Catch(Exception)
       {
              throw;
       }
}

very bad practice of exception handling. It will hit the performance while throwing the exception, Never do it.

4. Don't use the catch exception object to throw exception if you need to catch the exception and then throw. It looses the stack trace details.
Ex:
void Method()
{
       try
       {
              //Code
       }
       Catch(Exception ex)
       {
             //Logging exception here or doing something.
              throw ex;
       }
}

the piece of code "throw ex" is bad practice instead you should write just "throw;"



5. Don't catch exception if you are not doing anything with the exception details.

6. All your public method must have 'try-catch' block instead of having it in private methods.
Note: Handle exception in private methods only if have no intention to throw exception to calling method.

7. Don't keep your catch block dumb.
Ex.
bool Method()
{
       bool status;
       try
       {
              //Code
       }
       Catch{}
       return status;
}

In above code you basically eat the exception. In this case if someone is calling this method he will always get returned FALSE and calling method will never know why return status is false.

8. Avoid returning "ex.Message"  Or "ex.InnerException.Message" as a return statement.
Ex:
string Method()
{
       try
       {
              //Code
       }
       catch (Exception ex)
      {
             return ex.Message; OR return ex.InnerException.Message;
      }
       return "";
}

Exception details always contains crucial and confidential information as it contains detail about the code, logic, resource details etc. So by writing above code you are basically creating a security risk by passing information to calling method.

9. Always use Custom Exception to throw exception when it is raised by service which is going to get consumed by different consumers directly.
Ex. If you are developing a service library or an API which can be consumed by different consumer. In this case you should not throw actual exception as it contains details about you business logic.

10. Don't forget to use try-catch or you will end up showing yellow page with exception details to the user.

Thank you for reading.
Feel free to provide your feedback/comments.