8

I've encountered a class which extends Exception :

public class MyException extends Exception
{
    public MyException()
    {
        super();
    }

    public MyException(final String argMessage, final Throwable argCause)
    {
        super(argMessage, argCause);
    }

    public MyException(final String argMessage)
    {
        super(argMessage);
    }

    public MyException(final Throwable argCause)
    {
        super(argCause);
    }


}

Is it not pointless extening exception this way since all of the overriding constructors are just calling the super class Exception ?

user701254
  • 3,935
  • 7
  • 42
  • 53
  • possible duplicate of [Subclassing Exception in Java: when isn't a custom message "good enough"?](http://stackoverflow.com/questions/9366425/subclassing-exception-in-java-when-isnt-a-custom-message-good-enough) – Tomasz Nurkiewicz May 25 '12 at 08:58

3 Answers3

10

No, it is not pointless. You can catch the specific exception this way and handle it specifically, rather then catching a general Exception, which might not be handled in all cases.

With this, you can do:

try { 
  foo();
} catch (MyException e) {
  handleMyException(e);
}

Which is not possible if you do not know how to handle a general Exception, but you can handle MyException better.

It is also improves readability - it is better to declare a method as throws MyException (with better name usually) then throws Exception - you know what can go wrong much better this way.

amit
  • 175,853
  • 27
  • 231
  • 333
5

Yes, there's a reason. It allows you to differentiate the type of your exceptions.

Suppose this following code:

try {
    // some instructions
} catch (MyFirstException firstException) {
    // Handler for the first exception
} catch (MySecondException secondException) {
    // Handler for the first exception
} catch (Exception exception) {
    // Handler for all other exceptions
}

Event if the MyFirstException and MySecondException inherit from Exception and override all methods, you can distinguish them in the catch blocks. So, you can have different handlers for both exceptions.

Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
0

when you would always do a catch (Exception e) you would actually catch each and every subclass of Exception, this specifically also applies to RuntimeExceptions which you usually don't want to catch. This can only be made worse by catching Throwable

Korgen
  • 5,191
  • 1
  • 29
  • 43