Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why extend Exception class?

Tags:

java

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 ?

like image 480
user701254 Avatar asked May 25 '12 08:05

user701254


1 Answers

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.

like image 86
amit Avatar answered Oct 06 '22 00:10

amit