When to choose checked and unchecked exceptions

前端 未结 18 2305
南方客
南方客 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 04:47

    I think we can think about exeptions from several questions:

    why does exeption happen? What can we do when it happens

    by mistake, a bug. such as a method of null object is called.

    String name = null;
    ... // some logics
    System.out.print(name.length()); // name is still null here
    

    This kind of exception should be fixed during test. Otherwise, it breaks the production, and you got a very high bug which needs to be fixed immediately. This kind of exceptions do not need be checked.

    by input from external, you cannot control or trust the output of external service.

    String name = ExternalService.getName(); // return null
    System.out.print(name.length());    // name is null here
    

    Here, you may need to check whether the name is null if you want to continue when it is null, otherwise, you can let it alone and it will stop here and give the caller the runtime exception. This kind of exceptions do not need be checked.

    by runtime exception from external, you cannot control or trust the external service.

    Here, you may need to catch all exceptions from ExternalService if you want to continue when it happens, otherwise, you can let it alone and it will stop here and give the caller the runtime exception.

    by checked exception from external, you cannot control or trust the external service.

    Here, you may need to catch all exceptions from ExternalService if you want to continue when it happens, otherwise, you can let it alone and it will stop here and give the caller the runtime exception.

    In this case, do we need to know what kind of exception happened in ExternalService? It depends:

    1. if you can handle some kinds of exceptions, you need to catch them and process. For others, bubble them.

    2. if you need log or response to user the specific execption, you can catch them. For others, bubble them.

提交回复
热议问题