When to use try/catch blocks?

后端 未结 4 1676
时光取名叫无心
时光取名叫无心 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 13:09

    Like some others have said, you want to use try-catch blocks around code that can throw an Exception AND code that you are prepared to deal with.

    Regarding your particular examples, File.Delete can throw a number of exceptions, for example, IOException, UnauthorizedAccessException. What would you want your application to do in those situations? If you try to delete the file but someone somewhere else is using it, you will get an IOException.

    try
    {    
        File.Delete(pgpdFilename + "_archive")
    }
    catch(IOException)
    {
        UtilityLogger.LogToFile("File is in use, could not overwrite.");
       //do something else meaningful to your application
       //perhaps save it under a different name or something
    }
    

    Also, keep in mind that if this does fail, then the File.Move you do outside of your if block next will also fail (again to an IOException - since the file was not deleted it is still there which will cause the move to fail).

提交回复
热议问题