开发者

When to wrap exceptions

开发者 https://www.devze.com 2023-02-01 08:16 出处:网络
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.

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?

I开发者_如何学Cs 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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号