4

I worked with the IBM Rational Software Architect for Websphere Software(RAD) and ran the code analyzer. I got the warning said the custom java Exception class should be final. But there is no proper reason for that. Anyhow for some requirments we have to extend the custom exception classes to maintain the exception hierarchy. So the final is no use. In some cases if we want to restrict the object creation we can mark the contructor as private.

So, can any body please let me know why the custom exception class should be final?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Java-Seekar
  • 1,720
  • 5
  • 30
  • 52

4 Answers4

4

I would refer you to the book Effective Java : Josh Bloch says with good arguments to mark classes final or else document the extension points to preserve immutability and to protect from unexpected behavior.

I am referring to Item 17 (Design and document for inheritance or else prohibit it)

In any case, this might just be a recommendation and if you are convinced you could ignore it - it is just to make sure you have thought about it.

Scorpion
  • 3,938
  • 24
  • 37
0

your custom exception class will extend Exception class i believe. This custom class will be specific to the exception you wish to handle. So unless you really wish to add another level of hierarchy to it, making this class final makes sense. If you wish to make another custom exception class you can do so by extending exception class again. Also you are getting a warning saying it must be final but if you have some requirement that needs more level of inheritance hierarchy you can define your class to be non final.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

The only reason to make a class Final is avoiding it to get extend by some other class. With this in mind, its upto you whether you want to make the class final or not.

roger_that
  • 9,493
  • 18
  • 66
  • 102
0

A good alternative to making a class 'final' would be to make its constructors private and provide static factories instead (also described in Josh Bloch's book). But of course, as it has already been said, it depends what's the purpose of your class.