Why should we write custom exception classes in Java

前端 未结 6 1771
执念已碎
执念已碎 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:13

    Well, simply put, if you do not need special exception class, you should not make one. If you do, then you make one. There's no magic to it really.

    If you're making a library, then you should of course think from the point of view of the developers using the library (even if it is just you): does your library throw exceptions for specific reasons and could the library user possibly want to catch specifically these, because they can realistically do something about it (just logging isn't reason enough, IMO).

    Example with standard exception classes: Caller of a method might want to convert IndexOutOfBoundsException to null return value, while letting other exceptions to propagate normally.

    If you want your custom exception to be handled in default ways, you extend right existing exception class, such as IOException. You can then catch your specific IO exception when you want to do something specific just there, but also let it be handled like any other IOException when you don't need special handling (can't do anything useful to recover).

    If you have a totally custom exception which should never be caught by a superclass catch, which always should have specific catch block, then you extend Exception directly.

    I think it's pretty rare to need to extend RuntimeException, because if it an exception meant to be caught it should be Exception subclass, and if it's meant to end the program or just generate log output, then it should be covered by default RuntimeException implementations with custom message string.

提交回复
热议问题