I have a three layer structure
1. Presentation layer
2. Business layer
3. Data Layer
The Presentation layer interacts with the business layer via a service facade . Now I am confused on where should I throw my exceptions , where should I log them and where should I catch and swallow them . Currently I am swallowing my exception in my presentation layer after logging , whereas I am logging and throwing them everywhere else . This results in an exception getting logged thrice . That is not a huge concern , but I wanted to know the best practice regarding this .
For example :
Presentation layer code :
try
{
UserService.GetAllUsers() ;
}
catch(Exception ex )
{
Logger.log(ex) // exception gets logged here
// redirect to a friendly user error page
}
UserService Layer Code
try
{
IUserDAO userDAO = ServiceRegistry.GetRegistry().GetDAOFactory().GetUserDAO() ;
return userDao.GetAllUsers() ;
}
catch ( Exception ex)
{
Logger.log(ex) ; // and here !
throw;
}
DAOLayer Code
try
{
// All db interaction code
}
catch(Exception ex)
{
Logger.log(ex) //and here !!
throw ;
}
It’s definitely unnecessary to put every piece of code in a try-catch block. For example, if an exception occurs in your ‘DAOLayer’ your log file will contain the same exception 3 times…
Keep in mind the golden rule with exceptions – exceptions should be exceptional! This usually means that you should only catch exceptions that you are able to handle – all other exceptions you should ignore – a handler at a higher level should handle these.
If you are concerned that an unhandled exception will crash your application (and rightfully so) you should take a look at the 2 events that .Net exposes for handling unhandled exception. The first is AppDomain.CurrentDomain.UnhandledException and the seconds is Application.ThreadException (which is in the Windows.Forms namespace).