Why throwing a general Exception in method is bad? [duplicate]

余生颓废 提交于 2021-02-05 12:17:21

问题


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()
        }     
    }

回答1:


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.

For example, Float.parseFloat() throws :

1) NullPointerException --> if the string is null

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

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.



来源:https://stackoverflow.com/questions/39500595/why-throwing-a-general-exception-in-method-is-bad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!