Clean Code Notes(第七章 错误处理)

278 阅读1分钟

1.使用异常而不是返回码

代码产生错误直接抛出异常,避免使用错误码进行判断的方式。

2.先写try catch final

优先写出try catch结构,再按照tdd的方式完成代码。

3.不在方法上直接抛出异常

如果一个方法在最底层抛出了异常但是没有处理的话,那么最终其顶层的所有方法都需要加上throw关键字,这是不可行的。

public class testThrowException {
    public static void test(){
        try {
            throw new RuntimeException();
        }catch (Exception e){
            System.out.println("exception is throw");
        }finally {
        }
    }
}

public class testException {
    public void test() {
        testThrowException.test();
    }

    public static void main(String[] args) {
        new testException().test();
    }
}

4.给出异常的明确错误信息

即在抛出异常时,要在异常中带上详细的错误message,这样当产生异常后,可以快速定位异常的位置以及错误原因。

5.对异常进行分类

不同的异常编写对应不同的类,明确区分不同的异常。

6.特例模式

image.png

7.别返回null值

image.png

8.别传递null值