为什么在方法中抛出一般Exception不好? [英] Why throwing a general Exception in method is bad?

查看:60
本文介绍了为什么在方法中抛出一般Exception不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么用方法抛出通用异常在Java中是不好的做法?

Why throwing by a method a general Exception is a bad practice in Java?

    class Test{
        public void ex() throws Exception{
            //...some code throwing for eg. IllegalAccesException()
        }     
    }

推荐答案

通过方法引发异常时,通常应该知道它是哪种异常.如果引发一般异常而不是特定异常,则在捕获到异常(如果引发)时,将丢失该异常的特定详细信息.

When you throw an exception by a method, you should normally know what kind of exception it is. if you throw a general exception rather a specific exception, you will loose the specific detail of the exception when catching the exception if raised.

例如,Float.parseFloat()抛出:

For example, Float.parseFloat() throws :

1)NullPointerException->如果字符串为空

1) NullPointerException --> if the string is null

2)NumberFormatException->如果字符串不包含可解析的浮点数.

2) NumberFormatException --> if the string does not contain a parsable float.

如果要抛出一般的异常"而不是"NullPointerException"和"NumberFormatException",则将无法知道是否由于字符串为空或字符串包含不可解析的浮点值而引发了异常.

If it was to throw general "Exception" instead of "NullPointerException" and of "NumberFormatException", there would be no way to know if the exception was raised because the string was null or the string contained non-parsable float value.

这篇关于为什么在方法中抛出一般Exception不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆