开发者

exception handling and (throw ex)

开发者 https://www.devze.com 2023-01-20 23:13 出处:网络
What is开发者_如何学C the best way to handle an exception? Also, why should I never write: catch (Exception ex) { throw ex; }

What is开发者_如何学C the best way to handle an exception?

Also, why should I never write:

catch (Exception ex) { throw ex; }


The best way to handle an exception is to do something meaningful in the catch block (the one which in your example contains throw ex). The definition of "meaningful" completely depends on your needs.

You should not do catch (Exception ex) { throw ex; } because that brakes the exception chain. It is perfectly fine to catch an exception, handle it and re-throw so that the calling code can see it, but you should be doing so like this:

catch (Exception ex) { /* handling code; */ throw; } 


Why would you catch the expection to just throw it again, if you were to catch the exception and do something other than just throw it, it would be fine!

try 
{
}
catch(Exception ex)
{
 // do something like log the exception
 throw ex; // let another catch block handle the expection.
}
0

精彩评论

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