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. I would like to design my own exceptions and include them into my methods, forcing developers to catch and do appropriate work.
For example, if you have a method to get a user from the database based on a name.
public User getUser(String name);
However, it is possible that the user might be null and it is common to forget to check this before using a User's public method.
User user = getUser("adam");
int age = user.getAge();
which would result in NullPointerException and a crash. However, if I made a check, before returning the user-object, if its null and throw an 'UserIsNullException':
public User getUser(String name) throws UserIsNullException;
I force the implementor to think and act:
try {
User user = getUser("adam");
int age = user.getAge();
}catch( UserIsNullException e) {
}
It makes the code much safer for unexpected crashes and eliminates more bugs. Let say the website has hundreds of visitors per hour and this design pattern is used pretty much everywhere.
How would such a design approach effect performance? Do the benefits out-weigh the cost or is it just plain bad coding?
Thanks for any help!
UPDATE! To be clear, my attention is not wrap a NullPointerException, as my example might suggest. The goal is to force the implementer to write a try/catch, saving the head ache of a real crash since a:
user == null
was forgotten. The question concerns comparing these two design models:
int age;
try {
User user = getUser("adam");
age = user.getAge();
}catch( UserIsNullException e) {
age = 0;
}
versus:
int age;
User user = getUser("adam");
if( user != null ) {
age = user.getAge();
} else {
age = 0;
}