C# Nested Try Catch statements or methods?

2019-04-18 08:23发布

Simple best practice question.

Should you nest try catch statements or just use methods.

For instance, if you have a method that opens a file does work and closes the file, you would have the open and close outside the try catch, or rather the close in the finally block.

Now if your open method fails, the method would assert right? So should your wrap that in a try catch block or should that be called from another method, which in turn as a try catch block?

8条回答
不美不萌又怎样
2楼-- · 2019-04-18 08:49

This is a style question but for me I try to never have more than one level of try/catch/finally nesting in a single method. At the point you hit a nested try, you've almost certainly violated the 1 function = 1 operation principal and should use a second method.

查看更多
叛逆
3楼-- · 2019-04-18 08:55

Depends on what you are trying to do, but in most cases, nested try/catches are a sign of an over-complex function (or of a programmer who doesn't quite know how exceptions work!).

In the case of the open file, I'd use an IDisposable holder and a using clause, and so forgo the need of any explicit try/catch.

查看更多
登录 后发表回答