Exception handling

This article is part of our exception handling article series.
Learn more about exception handling

Fulfil the contract or die trying

Method names are like a contract. When the code executes, the method it should deliver what it promised. If it cannot, an exception should be thrown.

Consider the following method:

public User GetUser(int userId);

What should it return if the user cannot be found? null? No! The method clearly states "Get user". It doesn't say PleaseTryToFindTheUser(int userId). It also has a userId as an argument. A userId is rarely remembered and manually entered by a user, instead the userId have most likely been provided by another part of the code.

Those two facts combined makes it clear that an exception should be thrown if the specified user could not be returned.

Conclusion

Each time you write a method. Stop. Think about the method name and what it promises.

Go through the code and make sure that it either delivers the promised result or throw an exception.