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
{
}

No comments:

Post a Comment