When is it OK to use exception handling for business logic?

后端 未结 5 1005
栀梦
栀梦 2020-12-02 22:45

I think it is accepted that as a general rule in Java (and perhaps any language with exception handling) one should try to avoid using exception handling to actually handle

5条回答
  •  难免孤独
    2020-12-02 23:42

    If you are dealing with an error condition which is actually a part of the business logic, it is OK to use Exceptions. For example:

    try{
       // register new user
       if(getUser(name) != null)
          throw new MyAppException("Such user already exists");
       //other registration steps......
    }catch(MyAppException ex){
       sendMessage(ex.getMessage());
    }
    

提交回复
热议问题