Throwing and Catching Exceptions

Tutorial 2 of 5

1. Introduction

In this tutorial, we'll cover the important topic of throwing and catching exceptions in C++. The goal is to teach you how to signal and handle exceptions, which will make your code more robust and less prone to crashes.

By the end of this tutorial, you will be able to understand what exceptions are, how to throw and catch them, and why they're an important part of programming in C++.

Prerequisites: A basic understanding of C++ and its syntax.

2. Step-by-Step Guide

What are Exceptions?

Exceptions are runtime errors that disrupt the normal flow of program execution. They usually occur due to some illegal operation in the code.

Throwing Exceptions

To throw an exception, we use the throw keyword. It's often used inside a try block when a condition that might lead to an exception is checked.

Catching Exceptions

Exceptions are caught using catch blocks. A catch block follows a try block and specifies the type of exception it can handle.

Why use Exceptions?

Without exception handling, an error encountered in the program would lead to termination. With exceptions, we can handle errors and prevent sudden termination.

3. Code Examples

Example 1: Basic Throw and Catch

try {
    throw "This is an exception";
}
catch (const char* e) {
    std::cout << "Caught exception: " << e << std::endl;
}

In this code, we throw a string exception and catch it. The catch block prints the exception string to the console. The output would be Caught exception: This is an exception.

Example 2: Multiple Catch Blocks

try {
    throw 10;
}
catch (int e) {
    std::cout << "Caught an integer exception: " << e << std::endl;
}
catch (...) {
    std::cout << "Caught an unknown exception" << std::endl;
}

Here, we throw an integer exception. The first catch block catches it. If the exception were of any other type, the second catch block (with the ellipsis) would catch it. The output would be Caught an integer exception: 10.

4. Summary

In this tutorial, we've learned what exceptions are, how to throw and catch them, and why they're used in C++. The next step in learning would be to explore more complex examples and scenarios, and perhaps to learn about custom exceptions.

5. Practice Exercises

Exercise 1

Write a program where you throw an integer, a character, and a string exception from inside a try block, and catch them in separate catch blocks.

Exercise 2

Write a function that takes an integer as an argument and throws an exception if the integer is negative.

Exercise 3

Write a function that takes a pointer as an argument and throws a custom exception if the pointer is null.

For each exercise, think about the best way to structure your try and catch blocks, and be sure to test your code thoroughly.

Happy Coding!