In C#, how do I know which exceptions to catch?

前端 未结 11 1371
抹茶落季
抹茶落季 2020-12-30 08:33

I\'ve gotten in the habit of using a general catch statement and I handle those exceptions in a general manner. Is this bad practice? If so, how do I know which specific exc

11条回答
  •  感动是毒
    2020-12-30 09:07

    Yes, that is bad practice. Rule of thumb: "catch the exceptions you are in a position to respond to, let the other ones go."

    try {
        File.Open(usersChosenFile, FileMode.Open);
    } catch(FileNotFoundException) {
        // tell the user the file is gone, give them a chance to respond
        // this is good
    } catch(UnauthorizedAccessException) {
        // this is good too
    } catch(Exception) {
        // what did you just catch? Who knows. What if its OutOfMemoryException?
        // Do you really want to deal with that here? Let this one go by
    }
    

提交回复
热议问题