java的接口如何设计异常的理解

对于写接口时候,一直不太合理的写try-catch和throws。简单记录下心得。

try-catch捕获异常时候,在catch中进行日志的记录时候,
建议使用log.error("方法名或者可检索到的语句:",e),不建议使用e.getMessage()。
public void test02(){
        try {
            int a = 1 / 0;
        }catch (Exception e){
            //建议使用
            log.error("com.ethan.controller.NoTmsTest.test02:",e);
            //不建议使用
            log.error("com.ethan.controller.NoTmsTest.test02:",e.getMessage());
        }
    }

------输出如下

2021-11-25 19:20:32,308  ERROR main com.ethan.controller.NoTmsTest  [//] com.ethan.controller.NoTmsTest.test02:
java.lang.ArithmeticException: / by zero
	at com.sinolife.tms.backstage.controller.NoTmsTest.test02(NoTmsTest.java:36)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)

2021-11-25 19:20:32,312  ERROR main com.ethan.controller.NoTmsTest  [//]   com.ethan.controller.NoTmsTest.test02B:

其中,

  1. 使用方法名或者可检索的语句,可以准备的通过日志定位到错误的位置,不然很难通过日志去检索到当前接口的错误地方;
  2. 使用e而不是e.getMessage(),是因为e可以显示出报错的原因,而e.getMessage()不会显示报错原因。
  3. 其实最重要的原因是我们要很方便的能够通过无穷尽的日志文件中定位到我们出错的接口,并且看到详细的报错信息。
原文地址:https://www.cnblogs.com/ethanSung/p/15604449.html