Why extend the exception class?

I came across a class that 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); } } 

Isn't that a pointless exception for an exception in this way, since all the main constructors simply call the superclass Exception?

+7
source share
3 answers

No, this is not meaningless. You can catch specific exception this way and handle it specifically, rather than catching a generic Exception that might not be handled in all cases.

With this you can do:

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

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

It also improves readability - it is better to declare the method as throws MyException (with the best name usually), and then throws Exception - you know that may not go as well as better.

+8
source

Yes, there is a reason. This allows you to distinguish between types of exceptions.

Assume the 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 MyFirstException and MySecondException inherit from Exception and override all methods, you can distinguish them in catch blocks. This way you can have different handlers for both exceptions.

+5
source

when you always catch (Exception e) , you really catch every subclass of Exception , this also applies to RuntimeException , which you usually don't want to catch. This can only be exacerbated by fishing Throwable

0
source

All Articles