In Java, what is the difference between catch a generic exception and a specific exception (eg. IOException?)

前端 未结 7 1657
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 14:39

Currently I\'m catching only generic exceptions, but i want change this to catch the specific exceptions, but what is the advantage of this?

7条回答
  •  孤城傲影
    2020-12-03 15:13

    A good example that shows the ability to handle issues based on the type of issue that occurred:

    try {
      // open a file based on its file name
    } catch (FileNotFoundException e) {
      // indicate that the user specified a file that doesn't exist.
      // reopen file selection dialog box.
    } catch (IOException e) {
      // indicate that the file cannot be opened.
    }
    

    while the corresponding:

    try {
      // open a file based on its file name.
    } catch (Exception e) {
      // indicate that something was wrong
      // display the exception's "reason" string.
    }
    

    The latter example provides no means for handling the exception based on what issue occurred. All issues get handled the same way.

提交回复
热议问题