Try/Multi-Catch vs Single Catch

后端 未结 5 952
北荒
北荒 2021-01-11 17:16

While adding a try/catch block in Eclipse, it gave me the option of \"Surround with try/multi-catch\" or \"Surround with try/catch.\"

This is the try/multi-catch:

5条回答
  •  伪装坚强ぢ
    2021-01-11 17:44

    Look, the actual utility of try-catch structures is that you can apply a specific error-handling function to a specific exception. In your case, it doesn't appear that you want anything to happen other than a stack trace to be printed. If I, for instance, wanted the window to close if a FileIOException was thrown, and I wanted simply an error message to appear if any other exception occurs, then it would be useful to have multiple try-catch blocks as you wrote in the second code block. In this application, though, you may just want to have a catch like this:

    try {
        save.load(new FileInputStream(file.getAbsolutePath()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    And that will print a strack trace for ALL exceptions. :)

提交回复
热议问题