I'm little bit confused about handling exceptions within a hierarchy of methods.
Let's say, I've a class Logger
in a class library project. Please have a look on the following code-
namespace MyLibrary
{
public class Logger
{
//exposed to other project
public static void CreateLog(String message)
{
try
{
WriteInFile(message); //calling the method below
}
catch (Exception Ex)
{
throw Ex;
}
}
//private method
private static void WriteInFile(String message)
{
try
{
//Writing in a file
}
catch (Exception Ex)
{
throw Ex;
}
}
}
}
Let's assume, I'm using that library in an ASP.NET MVC project. Code -
namespace MvcProject.Controllers
{
public class HomeController : Controller
{
public ActionResult DoSomething()
{
try
{
Logger.CreateLog("some text.");
}
catch (Exception Ex)
{
//Exception is handled here.
}
return View();
}
}
}
Hierarchy: DoSomething() -> CreateLog() -> WriteInFile()
All the three methods have try.. catch..
blocks. My questions are-
Do I actually need try.. catch
in CreateLog()
and WriteInFile()
method?
If I use that in all the methods, does it have any performance impact?
This is a fictitious example to get the problem explained.
It would be more useful for me if you post an answer with a revised code block that you suggest.
Thank you.
Do I actually need try.. catch in every method?
No. In fact, it's harming your diagnostics by cutting off the stack trace - you won't be able to see the original full stack trace. You could fix that by just using:
throw;
instead of
throw Ex;
... but basically the try/catch blocks are just adding cruft here. Get rid of them.
If I use that in all the methods, does it have any performance impact?
Only if an exception is thrown - but then it's potentially making it slower by recomputing the stack trace each time. I wouldn't worry about the performance though - worry about readability of code (and the effect on stack traces) first.
See more on this question at Stackoverflow