0

Which one is a good combination with UI layers try-catch and a good practice in n-tier application and why?

1.

 try
    {
     //Statements
    }
    catch
    {
      throw
    }
    finally
    {
     //cleanup codes
    }

OR

2.

 try
    {
      // statements
    }
    catch(Exception ex)
    {
    }
    finally
    {
     // clean up
    }

and in UI layer

try{
}
catch(Exception ex)
{
 Log(ex);
}
finally
{
  //clean up
}
  • 2
    possible duplicate of [Where to put try catch](http://stackoverflow.com/questions/523875/where-to-put-try-catch) – slugster Jan 08 '11 at 11:58
  • 1
    Also covered here: [How and where do we write try catch block to handle Exception](http://stackoverflow.com/questions/2430823/how-and-where-do-we-write-try-catch-block-to-handle-exception). These were just two questions i picked from the *Related questions* panel to the right without even doing a search. – slugster Jan 08 '11 at 12:00
  • Whatever you are doing where it says "clean up" probably indicates that the whole thing should be replacing with a `using` statement. – Cody Gray - on strike Jan 08 '11 at 12:51

2 Answers2

1

In the first one, the catch and throw is totally pointless, you should just use a try and finally if you want to ensure the cleanup.

The second is dangerous and should never ever be used. The code should not contain a catch that swallows every exception and just ignores it without even an explanation. In the rare case that you need to catch an exception and ignore it, you should try to limit it to a specific type of exception, and you should always include a comment in the code explaining why the exception is ignored.

The third example works fine. I assume that you have some more exception handling inside the try block that catches the specific exception types that you anticipate, and informs the user of the problem when needed.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

A common practice is to use try/finally (or the using statement) in the business/service layer to ensure resources are cleaned up properly.

At a physical tier boundary you might want to long exceptions, so you might have something like the following:

try
{
} 
catch(Exception ex)
{
   ... log exception
   throw;
}

And maybe a top-level exception handler (try/catch) in the UI tier.

Joe
  • 122,218
  • 32
  • 205
  • 338