Would you ever NOT catch an exception, or throw an exception that won't be caught?

前端 未结 14 858
感情败类
感情败类 2021-01-03 09:49

I\'ve dealt with instances where I would throw/rethrow an exception knowing that the code surrounding it would catch the specific exception. But is there any time you would

14条回答
  •  执笔经年
    2021-01-03 10:15

    You probably wouldn't want an uncaught exception anywhere where the end-users can see it, but it is often acceptable to let clients of your API (other programmers) decide how to handle exceptions.

    For example, suppose you are designing a Java class library. You expose a public method that takes in a String. In your application, a null input value would cause an error. Instead of handling the error yourself, it would be acceptable to check for a null value, then throw an IllegalArgumentException.

    You must, of course, document that your method throws this exception in this circumstance. This behavior becomes part of your method's contract.

提交回复
热议问题