How to Catch Exceptions In C++?

11 minutes read

In C++, exceptions can be caught using try and catch blocks. The try block contains the code that may generate an exception, and the catch block handles the exception if it occurs. Here is how you can catch exceptions in C++:

  1. Place the code that may throw an exception inside a try block.
  2. Immediately after the try block, include a catch block to handle the exception.
  3. Specify the type of exception you want to catch after the catch keyword. This ensures that only exceptions of that type (or derived from it) will be caught.
  4. Inside the catch block, write the code to handle the exception accordingly.


For example, let's say you have a function that performs division and can potentially throw a division by zero exception:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <iostream>

int divide(int a, int b) {
    if (b == 0) {
        throw "Division by zero exception";
    }
    return a / b;
}

int main() {
    try {
        int result = divide(10, 0);
        std::cout << "Result: " << result << std::endl;
    } catch (const char* e) {
        std::cout << "Exception caught: " << e << std::endl;
    }
}


In the above code, the divide() function throws an exception when the divisor is zero. Inside the main() function, we put the divide() function call inside a try block. If an exception is thrown, the catch block will execute. In this case, the catch block catches the exception of type const char* (which is thrown as a string) and displays the error message.


Remember that you can have multiple catch blocks to handle different types of exceptions, starting with the more specific types and ending with more general ones. Additionally, you can catch all exceptions using a catch block without specifying any exception type, but this is generally not recommended as it may catch exceptions that were not intended to be caught.

Best C++ Books to Read in 2024

1
C# & C++: 5 Books in 1 - The #1 Coding Course from Beginner to Advanced (2023) (Computer Programming)

Rating is 5 out of 5

C# & C++: 5 Books in 1 - The #1 Coding Course from Beginner to Advanced (2023) (Computer Programming)

2
C Programming Language, 2nd Edition

Rating is 4.9 out of 5

C Programming Language, 2nd Edition

3
Effective C: An Introduction to Professional C Programming

Rating is 4.8 out of 5

Effective C: An Introduction to Professional C Programming

4
The C Programming Language

Rating is 4.6 out of 5

The C Programming Language

5
C Programming: A Modern Approach, 2nd Edition

Rating is 4.5 out of 5

C Programming: A Modern Approach, 2nd Edition

6
C Programming Absolute Beginner's Guide

Rating is 4.4 out of 5

C Programming Absolute Beginner's Guide

7
Learn C Programming: A beginner's guide to learning the most powerful and general-purpose programming language with ease, 2nd Edition

Rating is 4.3 out of 5

Learn C Programming: A beginner's guide to learning the most powerful and general-purpose programming language with ease, 2nd Edition

8
C Programming For Dummies (For Dummies (Computer/Tech))

Rating is 4.2 out of 5

C Programming For Dummies (For Dummies (Computer/Tech))


What is an exception in C++?

In C++, an exception is an error or unexpected circumstance that occurs during the execution of a program, which disrupts the normal flow of the program. It is used to handle errors or exceptional cases that may occur during runtime.


When an exception occurs, C++ provides a mechanism called exception handling to gracefully handle and recover from such errors. The program can throw an exception, and then the exception can be caught and handled in a specific catch block.


Exceptions are mainly used to handle scenarios such as divide-by-zero, file not found, out-of-memory, and other runtime errors. By using exceptions, the program can handle these errors in a controlled manner, rather than abruptly terminating the program.


What is the difference between exception and error in C++?

In C++, an exception is a type of error that can occur during the execution of a program. It is a condition that disrupts the normal flow of program execution. Exceptions are often caused by errors in the program logic or by external factors such as input/output failures or lack of system resources.


Errors, on the other hand, are more general and encompass all types of unintended or erroneous behavior in a program. This may include syntax errors, logical errors, runtime errors, or other unexpected conditions that prevent the program from executing correctly.


Exceptions are a specific mechanism provided by the C++ language to handle errors and enable the program to potentially recover from them. When an exception is thrown, the program jumps to a special section of code called an exception handler, which can handle the exception and determine the appropriate action to take.


Errors, on the other hand, do not have a predefined mechanism for handling and recovery like exceptions. They often require manual intervention to identify and fix the cause of the error.


In summary, exceptions are a specific type of error that can be handled and recovered from using the language's exception handling mechanism, while errors are a broader category encompassing all types of unintended or erroneous behavior in a program.


How to catch exceptions in C++ with try-catch-finally blocks?

In C++, exceptions can be caught and handled using try-catch-finally blocks. Here's an example of how you can catch and handle exceptions using these blocks:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
try {
  // Code that may throw an exception
  // ...
} catch (const ExceptionType1& e1) {
  // Handle exception of ExceptionType1
  // ...
} catch (const ExceptionType2& e2) {
  // Handle exception of ExceptionType2
  // ...
} catch (...) {
  // Catch all other exceptions
  // ...
} finally {
  // Code to be executed regardless of whether an exception was thrown or not
  // ...
}


Here's what each block does:

  1. The try block is used to wrap the code that might throw an exception. If any exception is thrown within this block, it will be caught and handled by one of the catch blocks.
  2. Each catch block specifies the type of exception it can handle. If the thrown exception matches the specified type, the corresponding block will be executed. You can have multiple catch blocks to handle different exception types.
  3. The catch (...) block is a catch-all block. It will be executed if no other catch block matches the thrown exception type. It can be useful for handling unexpected or unknown exceptions.
  4. The finally block is optional and is used to specify code that will be executed regardless of whether an exception was thrown or not.


Note that exceptions in C++ should be thrown using the throw keyword. For example:

1
throw ExceptionType();


By using these try-catch-finally blocks, you can catch and handle exceptions in your code, making it more robust and resilient.


What is exception safety in C++?

Exception safety refers to the ability of a program to deal with exceptions in a way that maintains object integrity and prevents resource leaks or other inconsistent program states. In C++, this concept is particularly important due to the language's support for exception handling.


There are three levels of exception safety in C++:

  1. No-throw guarantee: A function provides the highest level of exception safety by guaranteeing that it will not throw an exception under any circumstances. This ensures that the function will not impact the state of the program or its resources.
  2. Basic guarantee: A function provides the basic level of exception safety by ensuring that if an exception occurs, the program will remain in a valid state. Any resources allocated within the function will be correctly released, preventing memory leaks. However, the state of the program may be partially modified, and some objects may be left in an undefined or inconsistent state.
  3. Strong guarantee: A function provides the strongest level of exception safety by guaranteeing that if an exception is thrown, the program state will remain completely unchanged. If an operation within the function fails, all changes made previously will be rolled back, returning the program to its original state. This requires intermediate states to be maintained during an operation, ensuring that the program can safely resume execution after an exception.


Developers should strive for strong exception safety whenever possible, but achieving it can be challenging. It often requires careful use of techniques like transactional programming, resource management (such as smart pointers), and exception-safe coding practices.


By maintaining exception safety in C++ programs, developers can ensure robustness and prevent critical errors caused by exceptions.

Facebook Twitter LinkedIn Telegram Pocket