When to choose checked and unchecked exceptions

前端 未结 18 2904
南方客
南方客 2020-11-22 04:13

In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?

My inst

18条回答
  •  佛祖请我去吃肉
    2020-11-22 05:08

    Here is I want to share my opinion I have after many years of development experience:

    1. Checked exception. This is a part of business use case or call flow, this is a part of application logic we expect or not expect. For example connection rejected, condition is not satisfied etc. We need to handle it and show corresponding message to user with instructions what happened and what to do next (try again later etc). I usually call it post-processing exception or "user" exception.

    2. Unchecked exception. This is a part of programming exception, some mistake in software code programming (bug, defect) and reflects a way how programmers must use API as per documentation. If an external lib/framework doc says it expects to get data in some range and non null, because NPE or IllegalArgumentException will be thrown, programmer should expect it and use API correctly as per documentation. Otherwise the exception will be thrown. I usually call it pre-processing exception or "validation" exception.

    By target audience. Now let's talk about target audience or group of people the exceptions have been designed (as per my opinion):

    1. Checked exception. Target audience is users/clients.
    2. Unchecked exception. Target audience is developers. By other words unchecked exception are designed for developers only.

    By application development lifecycle phase.

    1. Checked exception is designed to exist during whole production lifecycle as normal and expected mechanism an application handles exceptional cases.
    2. Unchecked exception is designed to exist only during application development/testing lifecycle, all of them should be fixed during that time and should not be thrown when an application is running on production already.

    The reason why frameworks usually use unchecked exceptions (Spring for example) is that framework cannot determine the business logic of your application, this is up to developers to catch then and design own logic.

提交回复
热议问题