Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Exception Handling in C++: Try, Catch and Throw Keywords

Exception Handling in C++: Try, Catch and Throw Keywords

16 Jul 2024
Advanced
7.35K Views
17 min read
Learn with an interactive course and practical hands-on labs

Free C++ Course: Learn C++ In 21 Days

Exception Handling in C++

Exception Handling in C++ deals with the techniques to deal with unwanted and unexpected events occurring during the program execution. When learning C++, one must be ready to deal with errors, unexpected inputs, or other exceptions. However, exception handling in C++ makes it simpler, allowing your programs to run efficiently.

In this blog post on C++ tutorials, we'll discuss how to use C++ tools for exception handling. We'll understand C++ exceptions, exception classes, try, catch, and throw keywords, etc. To increase your knowledge of C++, you can also take our online C++ Training.

Read More: Top 50 Mostly Asked C++ Interview Questions and Answers

What is an Exception in C++?

Exceptions are runtime errors. Many a time, your program looks error-free during compilation. But, at the time of execution, some unexpected errors or events or objects come to the surface, and the program prints an error message and stops executing. Such unexpected happenings are calledexceptions in C++.

Example


int a = 8/0;

In the above example, the program will show an error during runtime because dividing by zero is undefined.

What is Exception Handling in C++?

Exception handling in C++ is a technique to deal with exceptions. It maintains your program flow despite runtime errors in the code and, thus, prevents unanticipated crashes. It facilitates troubleshooting by providing error details, cutting down on development time, and improving user happiness. It's essential for developing a trustworthy and safe programming environment.

What is an Exception Class in C++?

There are many standardsexceptions in C++. All the standard exceptions are defined in the exception Header file in C++. Thus, all the standard exception classes are derived from the std::exception Class in C++.

ExceptionDescription

std::exception

It is an exception as well as a parent class of all standard exceptions of C++.

std::logic_failure

This particular exception can be detected by reading any code.

std::runtime_error

This exception cannot be detected by reading any code.

std::bad_exception

This exception is used to handle unexpected exceptions in a C++ program.

std::bad_cast

This exception is generally thrown by dynamic_cast.

std::bad_typeid

This particular exception is generally thrown by typeid.

std::bad_alloc

This exception is generally thrown by new.

Read More: C++ Interview Interview Questions and Answers

Keywords for Exception Handling in C++

Keywords for Exception Handling in C++

  • try: the block of code defined under this statement is being tested for runtime errors.
  • throw: throws an exception when an error is detected. It is not necessary to use this keyword while using standard C++ exceptions.
  • catch: specifies the code block to be executed if an exception occurs in the try block.

Syntax


try {
 // code to check exceptions
 throw exception;
}

catch (exception) {
 // code to handle exceptions
}     

Every try block is followed by the catch Block. The throw Statement throws an exception, which is caught by the catch block. The catch block cannot be used without the try block

Example in C++ Compiler

// program to divide two numbers and throw an exception if the divisor is 0

#include <iostream>
using namespace std;

int main() {
    float numerator, denominator, result;
    numerator = 9;
    denominator = 0;

    try {
        // throw an exception if denominator is 0
        if (denominator == 0)
            throw 0; // Throwing an integer
        result = numerator / denominator; // if denominator not zero
        cout << numerator << " / " << denominator << " = " << result << endl;
    } 
    catch (int exception) { // Catching an integer
        cout << "Error: Cannot divide by " << exception << endl;
    }

    return 0;
}
  • In the above code, we have put the result = numerator / denominator in the try block because this statement must not be executed if the denominator is 0. If the denominator is 0, the statements after the throw statement in the try block is skipped.
  • The catch block catches the thrown exception as its parameter and executes the statements inside it.
  • Here, the exception is of type int. Therefore, the catch statement accepts a int parameter.
  • If there isn't any exception thrown, the catch block gets skipped.

Output

Error: Cannot divide by 0
  • You can also use the throw keyword to output a reference number, like a custom error number/code for organizing purposes:

    Example

    #include <iostream>
    using namespace std;
    int main() {
        int numerator, denominator, result;
        numerator = 8;
        denominator = 0;
    
        try {
            // Throw an exception if the denominator is 0
            if (denominator == 0)
                throw 505; // Throwing an integer
            result = numerator / denominator; // If the denominator is not zero
            cout << numerator << " / " << denominator << " = " << result << endl;
        }
        catch (int myNum) { // Catching an integer
            cout << "Error: Cannot divide by " << myNum << endl;
        }
    
        return 0;
    }
    

    Output

    Error: Cannot divide by 505
    

Handling All Types of Exceptions (...)

Suppose we do not know the types of exceptions that can occur in our try block or the throw type used in the try block; then, we can use the ellipsis symbol as our catch parameter. catch (...) is known as the catch-all exception handler.

Syntax


try {
 // code to check exceptions
}
catch (...) {
 // code to handle exceptions
}

Example

#include <iostream>
using namespace std;
int main() {
 float numerator, denominator, result;
 numerator = 9;
 denominator = 0;

 try {
 // throw an exception if the denominator is 0
 if (denominator == 0)
 throw 0;
 result = numerator / denominator; //if denominator not zero
 cout << numerator << " / " << denominator << " = " << result << endl;
 } 

 catch (...) {
 cout << "Error: Cannot divide by " << endl;
 }
 return 0;
}

Output

Error: Cannot divide by

Multiple Catch Statements in C++ Exception Handling

This is like an if else-if ladder. Here, we can use multiple catch statements for different kinds of exceptions that can occur from a single block of code in the try block.

Syntax


 try {
 // code to check exceptions
 } 
 catch (exception1) {
 // code to handle exception

 } 
 catch (exception2) {
 // code to handle exception
 }
 .
 .
 . 
 catch (...) {
 // code code to handle exception
 }
  • Here, our program matches the type of exception that occurred in the try block with the catch statements.
  • If the exception that occurred matches any of the normal catch statements, that particular catch block gets executed.
  • If the exception occurred, it matches none of the normal catch statements, the catch-all exception handler, catch (...) gets executed.
  • The catch (...) statement acts as the default catch statement. Therefore, it must always be the final block in the try...catch statement
  • It is not necessary to have a default catch block in the program.

Example in C++ Online Editor


#include <iostream>
 using namespace std;
 
 int main() {
 
 float numerator, denominator, arr[] = {1, 2, 3, 4, 5};
 int index;
 cout << "Enter array index: ";
 cin >> index;
 
 try {
 
 // throw exception if array is out of bounds
 if (index >= sizeof(arr))
 throw "Error: Array out of bounds!";
 
 // not executed if array is out of bounds
 cout << "Enter numerator: ";
 cin >> numerator;
 
 cout << "Enter denominator: ";
 cin >> denominator;
 
 // throw exception if denominator is 0
 if (denominator == 0)
 throw 0;
 
 // not executed if denominator is 0
 arr[index] = numerator / denominator;
 cout << arr[index] << endl;
 }
 
 // catch "Array out of bounds" exception
 catch (const char* msg) {
 cout << msg << endl;
 }
 // catch "Divide by 0" exception
 catch (float num) {
 cout << "Error: Cannot divide by " << num << endl;
 }
 
 // catch any other exception
 catch (...) {
 cout << "Unexpected exception!" << endl;
 }
 
 return 0; 
 }
 

In the above code, we are dividing two numbers and storing their result in an array arr at the index value given by the user. There can be two possible exceptions here:

  • Array index out of bounds: the indexvalue given by the user is greater than the size of the array
  • Divide by 0: If the denominator is 0.

If there occurs any other exception in the try block, it will be caught by the catch(...) statement.

Output

  • If the user enters a valid input.
     Enter array index: 3
     Enter numerator: 10
     Enter denominator: 2
     5
  • If the user inputs an invalid index
     Enter array index: 5
     Error: Array out of bounds!
  • If the denominator is 0
     Enter array index: 2
    Enter numerator: 8
    Enter denominator: 0
    Error: Cannot divide by 0
  • If any unexpected exception occurs
     Enter array index: 2
     Enter numerator: "sScholarHat" // Entering a string instead of a number
     Unexpected exception!
You can also read:
Summary

Unexpected errors that arise while a program is running can be handled with C++ exception handling. You can learn more about exception handling in C++ with examples in C++ courses, providing a flexible mechanism for managing both anticipated and unanticipated errors.

FAQs

Unexpected problems that occur while a program is running can be managed and recovered by using C++'s exception-handling framework.

Exception handling is primarily used to gently manage errors, ensuring that programs can bounce back from unusual circumstances without crashing.

try, catch, and, throw are all keywords that are used in exception handling.

If exceptions are used excessively, disadvantages of exception handling may include increased code complexity as well as overhead.

Unchecked exceptions (runtime exceptions) do not need to be explicitly handled; instead, they must be captured or expressly specified in the method signature for checked exceptions.

Try, catch, and throw the three exception keywords in C++ for catching all exceptions.

In C++, the words throw and try are used to raise custom exceptions, catch is used to catch exceptions, and try is used to enclose code that could throw exceptions.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this