Why should we write custom exception classes in Java

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

    I can think of several reasons:

    • Having multiple exception classes allows the programmer to be specific in their catch clauses, and only catch the exceptions they care about and know what to do with.
    • An exception class can carry information about the error that's caused the exception. For example, ArrayIndexOutOfBoundsException carries the offending array index, and SQL exceptions tends to carry database-specific error codes and messages.
    • Exception specifications -- that list exception classes -- can be used to check correctness at compile time.

提交回复
热议问题