Performance cost of coding “exception driven development” in Java?

前端 未结 14 1654
生来不讨喜
生来不讨喜 2020-12-09 10:28

Are there are any performance cost by creating, throwing and catching exceptions in Java?

I am planing to add \'exception driven development\' into a larger project.

14条回答
  •  [愿得一人]
    2020-12-09 10:58

    As per your last edit. I think ( as Tony suggested ) using the NullObject pattern would be more useful here.

    Consider this third scenario:

    class NullUser extends User {
    
        public static NullUser nullUser = new NullUser();
    
        private NullUser(){}
    
        public int getAge() {
            return 0;
        }
    }
    
    //Later...
    int age;
    
    User user = getUser("adam"); // return nullUser if not found.
    age = user.getAge();         // no catch, no if/null check, pure polymorphism
    

提交回复
热议问题