I always use a try catch when i am dealing with database related operations for eg.
try
{
DataContext.AddtoObjectname(obj);
DataContext.SaveChanges();
}
catch(Exception e)
{
throw new Exception("Problems adding object" + e);
}
But I read about try/catch affecting performance here –
Do try/catch blocks hurt performance when exceptions are not thrown?
So should I add try catch for something I am doing above or should i opt otherwise.Thanks for your help.
Try/Catch statements themselves don’t significantly affect performance, but throwing and catching lots of exceptions might.
In general, you want to make sure that you catch only relevant exceptions – otherwise you might be masking a bug in your application. In this case DataException or UpdateException are probably good candidates as they are the exceptions that will be thrown if something goes wrong in SaveChanges.
It seems that you’re catching the exception to add your own additional information to it. In that case, it’s always best to preserve the original exception as the Inner Exception.
I would also advise creating your own application specific exception type for this purpose.