Checked vs. Unchecked Exceptions in Service Layer

前端 未结 5 841
自闭症患者
自闭症患者 2020-12-13 10:59

I work on a project with a legacy service layer that returns null in many places if a requested record does not exist, or cannot be accessed due to the caller not being auth

5条回答
  •  余生分开走
    2020-12-13 11:50

    Unchecked exceptions help avoid code clutter. For example consider this code

        try
        {
            File file = new File("file");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String temp = "";
            StringBuilder result = new StringBuilder("");
            while ((temp = bufferedReader.readLine()) != null)
            {
                result.append(temp);
            }
            System.out.println(result);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    

    We handle two exception types, but if there is no actionable event that can occur by handling these exceptions, why catch them in the first place ? The answer is not to throw the checked exceptions, since eventually some class up the call hierarchy will have to handle it (Or it gets thrown to the JVM). If the developer is really interested in handling these, the catch the specific RuntimeException class that addresses the problem.

    Catch blocks that hold multiple exceptions go some way in reducing this clutter

提交回复
热议问题