When to use try/catch blocks?

后端 未结 4 1687
时光取名叫无心
时光取名叫无心 2020-11-27 12:21

I\'ve done my reading and understand what a Try/Catch block does and why it\'s important to use one. But I\'m stuck on knowing when/where to use them. Any advice?

4条回答
  •  一个人的身影
    2020-11-27 12:59

    I was taught to use try/catch/finally for any methods/classes where multiple errors could occur and that you can actually handle. Database transactions, FileSystem I/O, streaming, etc. Core logic usually doesn't require try/catch/finally.

    The great part about try/catch/finally is that you can have multiple catches so that you can create a series of exception handlers to deal with very specific error or use a general exception to catch whatever errors you don't see coming.

    In your case, you're using File.Exists which is good, but their maybe another problem with the disk that may throw another error that File.Exists cannot handle. Yes, it's a boolean method, but say the File is locked and what happens if you try to write to it? With the catch, you can plan for a rare scenario, but without try/catch/finally, you may be exposing the code to completely unforeseen conditions.

提交回复
热议问题