Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to wrap exceptions

Should I wrap every exception in a more meaningful exception? Wrapping meaning make the exception an inner exception of a new exception, and throw the "new" exception.

What factors do I need to think of when doing so?

Is the idea of wrapping exceptions because:

SQL Server could throw a bunch of exceptions from the T-SQL level. My C# API will only handle SQLException (handle meaning have a catch block for), so I'd want to wrap exceptions into a type my API can handle. This is just an example, SQL Server only throws SQLException, but is the concept right?

I assume that throwing the "new" exception, like mentioned above, would hold a cause which is not the real cause (which the dev needs to know), so would be more friendly for the end-user and hide sensitive implementation details of the real/first exception.

Thanks

like image 762
GurdeepS Avatar asked Dec 22 '10 21:12

GurdeepS


1 Answers

You are on the right track. It is a good practice to wrap exceptions when they are crossing application layer boundaries. The below two posts are good reads on best practices

  1. From MSDN
  2. Java specific
like image 102
Aravind Yarram Avatar answered Nov 14 '22 16:11

Aravind Yarram