Errors will happen. The question is how will you deal with them? The QA Friday from 2015 Dec-11 talked about this question. This episode explains C++ exceptions. C# also has exceptions. But C# is different enough to need its own episode.

A good way to summarize exceptions is that they allow you to detect and error condition in one place in your code and make sure that the error will eventually get handled in some other place in your code. This allows you to focus on writing your code without stopping to check for errors after every method call.

It also allows you to automatically clean up resources such as memory that needs to be freed or files that need to be closed. The technique for this relies on something called RAII which stands for “resource allocation is initialization.” Whenever you allocate some memory for example, instead of storing a pointer to that memory in a raw pointer, use a smart pointer such as std::shared_ptr which will take ownership of the pointer and make sure it gets deleted at the proper time when it’s no longer being used.

Exceptions give your program an efficient and consistent way to handle errors even in cases where the alternatives are either unreliable or difficult to enforce. You can’t use exception everywhere though. If you call a web service or a method in a COM component or some other remote service that’s outside of your application process, then you’ll have to use error codes or some other mechanism to inform the calling code that an error happened.