Introduction - Error Handling
Error handling is necessary for any computer program. (Literally any.) The way C++ programs typically handle C++ is through exceptions.
The way to think about it is that a program has several layers of code, each doing something. For example, the top layer is main, which is responsible for running the entire programming, and maybe main calls some other functions to do stuff, and those functions call other functions. What happens if a function several layers deep encounters an unexpected problem, or has some problem and needs advice on what to do? The answer, with exceptions, is that it throws the problem back up to it's previous layer, and that previous layer has to decide what to do. C++ Try-Catch Blocks
Try-Catch blocks are the basic mechanism used to handle exception handling, so let's look at a very basic C++ try-catch example.
There are a few things to note:
This is the general idea of try-catch blocks: they're really just control statements that help our program flow as we want it too. But we need to know a few exception types that we actually need to watch out for (otherwise, we could just handle everything with if statements). Let's look at a few.
Exceptions
We threw int and string before, but there are more useful types to throw to really be descriptive about what the error is. There are quite a few C++ exception types, and cppreference.com has created a very nice list.
Let's go over one specific example to see how this generally works.
Output:
Program started. Inside the function. Stop trying to access an invalid index! Program ended.
What we do it use normal code to check whether an error will occur or not, and if so, we throw that type of exception, which gets handled by the calling function.
Conclusion
Exceptions are an important part of any program. If we don't use exceptions, then our programs will crash, or we'll get undefined behavior.
Using exceptions is pretty simple, but exceptions should be thought about at the design level, and not just in the implementation level. (Meaning, you need to think about errors and exceptions when you first make your codebase.) To see some more advanced C++ exception tips, watch John Kalb's exception presentation on youtube.
Like this content and want more? Feel free to look around and find another blog post that interests you. You can also contact me through one of the various social media channels.
Twitter: @srcmake Discord: srcmake#3644 Youtube: srcmake Twitch: www.twitch.tv/srcmake Github: srcmake Comments are closed.
|
AuthorHi, I'm srcmake. I play video games and develop software. Pro-tip: Click the "DIRECTORY" button in the menu to find a list of blog posts.
License: All code and instructions are provided under the MIT License.
|