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

前端 未结 7 1617
隐瞒了意图╮
隐瞒了意图╮ 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:37

    Take this example:

    try {
     StringBuffer fileData = new StringBuffer(1000);
     BufferedReader reader = new BufferedReader(
       new FileReader(filePath));
     char[] buf = new char[1024];
     int numRead=0;
     while((numRead=reader.read(buf)) != -1){
       fileData.append(buf, 0, numRead);
     }
     reader.close();
     return fileData.toString();
    } catch (Exception e) {
     //do something generic - maybe log it
    }
    

    As it stands, it works...usually. However, with the vague error catching I can't really do anything except warn the user. If I caught the FileNotFoundException specifically, I could try another file. If I caught the IOException specifially, I could warn about something else. This example is a bit weak, but it may give you some idea.

    0 讨论(0)
提交回复
热议问题