Why should we write custom exception classes in Java

前端 未结 6 1773
执念已碎
执念已碎 2020-12-19 03:49

What is the purpose of writing custom exception classes when mostly what it does is same. For eg, NullPointerException:

class NullPointerException extends Ru         


        
6条回答
  •  再見小時候
    2020-12-19 04:34

    1. We will have a freedom to add few more methods into our Exception class which helps the client like rootCauseOfException(),description(),solution(),suggestions() etc. Can refer below link:
      https://stackoverflow.com/a/22698673

    2. If your project has interdependent modules then you can maintain exception hierarchy also in the same dependency hierarchy so that if you catch single Exception in base layer then all the interdependent modules exceptions will be caught.

    3. You can also mask some sensitive data like ip ,port etc before sending to client side. If custom exceptions are not used then some sensitive data can may get leaked to slient.

    4. You can provide your own exception message which can be easily understandable by client rather than java's exception message sometimes which may be hard to understand .

提交回复
热议问题