Powered by
/src$ make
  • Home
  • About
  • Directory
  • Contact
  • Home
  • About
  • Directory
  • Contact

C++ Error Handling For Beginners - Try-Catch and Exceptions Tutorial

11/16/2018

 

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. 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Copyright srcmake.com 2018.
// C++ Exception Code
#include <iostream>
#include <exception>
using namespace std;

// Declare that our function is expected to throw an int or a string exception.
void WillThrowException() throw (int, string)
    {
    // Do some stuff.
    cout << "Inside the function.\n";
    
    // Throw an exception
    throw 20;
    string s = "We never get to this line.\n";
    throw s;
    
    // Do some other stuff.
    cout << "Will never get here, since an exception is thrown.\n";
    }

int main()
    {
    cout << "Program started.\n";
    try
        {
        WillThrowException();
        cout << "This line of code never gets run, since the exception will be thrown before.\n";
        }
    // This catch handles an int exception, specifically.
    catch(int x) 
        {
        cout << "Caught an exception! Handle it here.\n";
        cout << x << endl;
        cout << "Hopefully we handled the exception.\n";
        }
    // This catch handles a string exception.
    catch(string s)
        {
        cout << "You can handle the string exception here.\n";
        }
        
    cout << "Program ended.\n";
    return 0;
    }
There are a few things to note:
  1. A try runs some code, and if an exception is thrown, it stops executing that block of code and runs the code in the appropriate catch block.
  2. Functions may declare the type of exceptions that they throw next to the function name. (This is good practice.) 
  3. Different exception types are possible. 
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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright srcmake.com 2018.
// C++ Exception Code
#include <iostream>
#include <exception>
using namespace std;

void BadIndex() throw (std::out_of_range)
    {
    cout << "Inside the function.\n";
    
    // Create an array of 5 elements.
    int arr[5];
    
    // Try to initialize the first 10 elements to 0. 
    for(int i = 0; i < 10; i++)
        {
        // Check if the user is trying to access an index they shouldn't.
        if(i < 0 || i >= 5)
            {
            // Bad index, so throw the exception.
            throw std::out_of_range ("Stop trying to access an invalid index!");
            }
        // If the index is in range, just do the thing we wanted too.
        else
            {
            arr[i] = 0;
            }
        }
        
    cout << "We'll never get here, since an exception is thrown.\n";
    }

int main()
    {
    cout << "Program started.\n";
    
    try
        {
        BadIndex();
        cout << "This line of code never gets run, since the exception will be thrown in the previous line.\n";
        }
    catch(std::out_of_range ex)
        {
        cout << ex.what() << endl;
        }
        
    cout << "Program ended.\n";
    return 0;
    }
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
References
1. www.cplusplus.com/doc/tutorial/exceptions/
​
2. www.geeksforgeeks.org/exception-handling-c/
​
3. en.cppreference.com/w/cpp/error/exception

Comments are closed.

    Author

    Hi, 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.
    Metamask tip button
    License: All code and instructions are provided under the MIT License.

    Discord

    Chat with me.


    Youtube

    Watch my videos.


    Twitter

    Get the latest news.


    Twitch

    See the me code live.


    Github

    My latest projects.

Powered by Create your own unique website with customizable templates.