0

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()
        }     
    }
Tom
  • 16,842
  • 17
  • 45
  • 54
EazyH
  • 57
  • 6
  • 2
    Why would returning `Object` be a bad practice in Java? Same reason. But even more so. Is the actual problem in your code, or is it from the JVM, or from the Operating System? – Elliott Frisch Sep 14 '16 at 22:32
  • Because it isn't specific. You may be throwing multiple types of exceptions in the method, and wrapping them all up with `Exception` makes your code less explicit. – Cache Staheli Sep 14 '16 at 22:33
  • If you have a new question, then create a new post. Manipulating an existing question to ask something new in there is not allowed. – Tom Sep 14 '16 at 23:29
  • You didin't understand my question, and marked it as duplicate, so i changed only the code to explain my problem better and now you're suggesting that it is a new question... I still, don't know the answer. GJ – EazyH Sep 14 '16 at 23:52

1 Answers1

3

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.

Christopher
  • 425
  • 3
  • 9