Checked vs. Unchecked Exceptions in Service Layer

前端 未结 5 804
自闭症患者
自闭症患者 2020-12-13 10:59

I work on a project with a legacy service layer that returns null in many places if a requested record does not exist, or cannot be accessed due to the caller not being auth

5条回答
  •  时光取名叫无心
    2020-12-13 11:39

    Generally it is a good practice to throw a RuntimeException when your code at the higher level can not handle it and can not do anything about the exception.

    In your case your API, will return some result if result is successfull, and should return null if there are no results found, and then throw an exception if there is anything that went wrong while performing the operation.

    The exception can be Unchecked, if you are just showing the error message to the user and doing nothing more about the problem.

    On the otherhand if you plan to take some alternate steps in case of problem, then you should be throwing an checked exception.

    For example, I have a code which is like -

    Deduct the payment and then Send shipment details. If(sending shipment details is not successfull) then refund the payment else send success mail.

    In the above logic, my logic of sending the shipping details should throw an checked exception becase, if there is any problem, then I have to refund the amount to the customer. If in this case I throw an unchecked exception, the only thing that happens that the user might get the error message.(Unless you catch the runtimeexception - Which is bad.)

    Thanks, Sathwick

提交回复
热议问题