JAVA Exception 处理注意事项

来源:互联网 发布:233什么意思网络语言 编辑:程序博客网 时间:2024/04/19 15:30

1,先catch子的Exception,再catch父的Exception,这一点比较好避免,违反了的话会有compile错误。

 

2,不要用一个catch Exception来处理所有的exceptions。

 

3,最早抛出exception:exception的信息能够更准确和详细的描述异常信息。

最迟catch exception,只有在能对catch的exception做具体的处理的时候才catch它。

 

4,不要把Exception吃掉,catch后不做任何事情。【运行后出了异常很难找啊,因为被吃了啊】

 

5,如果客户端能根据你抛出的exception做具体的处理,抛出checked exception,否则抛出unchecked exception。【抛出太多的checked exception会让method signature太繁琐】

 

6,在程序最高层对所有exception做处理,对于runtimeexception,log后继续抛出。

 

7,对exception做最详细的log:最好把StackTrace log下来。

public static String getExcpTraceInfo(Exception excp) {
        ByteArrayOutputStream expMsg = new ByteArrayOutputStream();
        PrintStream expout = new PrintStream(expMsg);
        excp.printStackTrace(expout);
        return expMsg.toString();
    }