The Wayback Machine - https://web.archive.org/web/20241120154012/https://www.geeksforgeeks.org/exception-handling-c/
Open In App

Exception Handling in C++

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. The process of handling these exceptions is called exception handling. Using the exception handling mechanism, the control from one part of the program where the exception occurred can be transferred to another part of the code.

So basically using exception handling in C++, we can handle the exceptions so that our program keeps running.

What is a C++ Exception?

An exception is an unexpected problem that arises during the execution of a program our program terminates suddenly with some errors/issues. Exception occurs during the running of the program (runtime).

Types of C++ Exception

There are two types of exceptions in C++

  1. Synchronous: Exceptions that happen when something goes wrong because of a mistake in the input data or when the program is not equipped to handle the current type of data it’s working with, such as dividing a number by zero.
  2. Asynchronous: Exceptions that are beyond the program’s control, such as disc failure, keyboard interrupts, etc.

C++ try and catch

C++ provides an inbuilt feature for Exception Handling. It can be done using the following specialized keywords: try, catch, and throw with each having a different purpose.

Syntax of try-catch in C++

try {         
// Code that might throw an exception
throw SomeExceptionType("Error message");
}
catch( ExceptionName e1 ) {
// catch block catches the exception that is thrown from try block
}

1. try in C++

The try keyword represents a block of code that may throw an exception placed inside the try block. It’s followed by one or more catch blocks. If an exception occurs, try block throws that exception.

2. catch in C++

The catch statement represents a block of code that is executed when a particular exception is thrown from the try block. The code to handle the exception is written inside the catch block.

3. throw in C++

An exception in C++ can be thrown using the throw keyword. When a program encounters a throw statement, then it immediately terminates the current function and starts finding a matching catch block to handle the thrown exception.

Note: Multiple catch statements can be used to catch different type of exceptions thrown by try block.

The try and catch keywords come in pairs: We use the try block to test some code and If the code throws an exception we will handle it in our catch block.

To understand how to handle exceptions and write robust code, our Complete C++ Course offers comprehensive lessons on exception handling and other error-handling mechanisms.

Why do we need Exception Handling in C++?

The following are the main advantages of exception handling over traditional error handling:

  1. Separation of Error Handling Code from Normal Code: There are always if-else conditions to handle errors in traditional error handling codes. These conditions and the code to handle errors get mixed up with the normal flow. This makes the code less readable and maintainable. With try/catch blocks, the code for error handling becomes separate from the normal flow.
     
  2. Functions/Methods can handle only the exceptions they choose: A function can throw many exceptions, but may choose to handle some of them. The other exceptions, which are thrown but not caught, can be handled by the caller. If the caller chooses not to catch them, then the exceptions are handled by the caller of the caller. 
    In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it).
     
  3. Grouping of Error Types: In C++, both basic types and objects can be thrown as exceptions. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, and categorize them according to their types.

Examples of Exception Handling in C++

The following examples demonstrate how to use a try-catch block to handle exceptions in C++.

Example 1

The below example demonstrates throw exceptions in C++.

C++
// C++ program to demonstate the use of try,catch and throw
// in exception handling.

#include <iostream>
#include <stdexcept>
using namespace std;

int main()
{

    // try block
    try {
        int numerator = 10;
        int denominator = 0;
        int res;

        // check if denominator is 0 then throw runtime
        // error.
        if (denominator == 0) {
            throw runtime_error(
                "Division by zero not allowed!");
        }

        // calculate result if no exception occurs
        res = numerator / denominator;
        //[printing result after division
        cout << "Result after division: " << res << endl;
    }
    // catch block to catch the thrown exception
    catch (const exception& e) {
        // print the exception
        cout << "Exception " << e.what() << endl;
    }

    return 0;
}

Output
Exception Division by zero not allowed!


Example 2

The following is a simple example to show exception handling in C++. The output of the program explains the flow of execution of try/catch blocks.

CPP
// C++ program to demonstate the use of try,catch and throw
// in exception handling.

#include <iostream>
using namespace std;

int main()
{
    int x = -1;

    // Some code
    cout << "Before try \n";

    // try block
    try {
        cout << "Inside try \n";
        if (x < 0) {
            // throwing an exception
            throw x;
            cout << "After throw (Never executed) \n";
        }
    }

    // catch block
    catch (int x) {
        cout << "Exception Caught \n";
    }

    cout << "After catch (Will be executed) \n";
    return 0;
}

Output
Before try 
Inside try 
Exception Caught 
After catch (Will be executed) 

Properties of Exception Handling in C++

Property 1

There is a special catch block called the ‘catch-all’ block, written as catch(…), that can be used to catch all types of exceptions.

Example

In the following program, an int is thrown as an exception, but there is no catch block for int, so the catch(…) block will be executed. 

CPP
// C++ program to demonstate the use of catch all
// in exception handling.

#include <iostream>
using namespace std;

int main()
{
    // try block
    try {

        // throw
        throw 10;
    }

    // catch block
    catch (char* excp) {
        cout << "Caught " << excp;
    }

    // catch all
    catch (...) {
        cout << "Default Exception\n";
    }
    return 0;
}

Output
Default Exception

Property 2

Implicit type conversion doesn’t happen for primitive types.

Example

In the following program, ‘a’ is not implicitly converted to int. 

CPP
//// C++ program to demonstate property 2: Implicit type
/// conversion doesn't happen for primitive types.
// in exception handling.

#include <iostream>
using namespace std;

int main()
{
    try {
        throw 'a';
    }
    catch (int x) {
        cout << "Caught " << x;
    }
    catch (...) {
        cout << "Default Exception\n";
    }
    return 0;
}

Output
Default Exception

Output: 

Default Exception

Property 3

If an exception is thrown and not caught anywhere, the program terminates abnormally.

Example

In the following program, a char is thrown, but there is no catch block to catch the char. 

CPP
// C++ program to demonstate property 3: If an exception is
// thrown and not caught anywhere, the program terminates
// abnormally in exception handling.

#include <iostream>
using namespace std;

int main()
{
    try {
        throw 'a';
    }
    catch (int x) {
        cout << "Caught ";
    }
    return 0;
}


Output

terminate called after throwing an instance of 'char'

We can change this abnormal termination behavior by writing our unexpected function.

Note: A derived class exception should be caught before a base class exception.

Like Java, the C++ library has a standard exception class which is the base class for all standard exceptions. All objects thrown by the components of the standard library are derived from this class. Therefore, all standard exceptions can be caught by catching this type.

Property 4

Unlike Java, in C++, all exceptions are unchecked, i.e., the compiler doesn’t check whether an exception is caught or not (See this for details). So, it is not necessary to specify all uncaught exceptions in a function declaration. However,exception-handling it’s a recommended practice to do so.

Example

The following program compiles fine, but ideally, the signature of fun() should list the unchecked exceptions. 

CPP
// C++ program to demonstate property 4 in exception
// handling.

#include <iostream>
using namespace std;

// This function signature is fine by the compiler, but not
// recommended. Ideally, the function should specify all
// uncaught exceptions and function signature should be
// "void fun(int *ptr, int x) throw (int *, int)"
void fun(int* ptr, int x)
{
    if (ptr == NULL)
        throw ptr;
    if (x == 0)
        throw x;
    /* Some functionality */
}

int main()
{
    try {
        fun(NULL, 0);
    }
    catch (...) {
        cout << "Caught exception from fun()";
    }
    return 0;
}

Output
Caught exception from fun()

A better way to write the above code: 

CPP
// C++ program to demonstate property 4 in better way

#include <iostream>
using namespace std;

// Here we specify the exceptions that this function
// throws.
void fun(int* ptr, int x) throw(
    int*, int) // Dynamic Exception specification
{
    if (ptr == NULL)
        throw ptr;
    if (x == 0)
        throw x;
    /* Some functionality */
}

int main()
{
    try {
        fun(NULL, 0);
    }
    catch (...) {
        cout << "Caught exception from fun()";
    }
    return 0;
}

Output
Caught exception from fun()

Note: The use of Dynamic Exception Specification has been deprecated since C++11. One of the reasons for it may be that it can randomly abort your program. This can happen when you throw an exception of another type which is not mentioned in the dynamic exception specification. Your program will abort itself because in that scenario, it calls (indirectly) terminate(), which by default calls abort().

Property 5

In C++, try/catch blocks can be nested. Also, an exception can be re-thrown using “throw; “. 

Example

The following program shows try/catch blocks nesting.

CPP
// C++ program to demonstrate try/catch blocks can be nested
// in C++

#include <iostream>
using namespace std;

int main()
{

    // nesting of try/catch
    try {
        try {
            throw 20;
        }
        catch (int n) {
            cout << "Handle Partially ";
            throw; // Re-throwing an exception
        }
    }
    catch (int n) {
        cout << "Handle remaining ";
    }
    return 0;
}

Output
Handle Partially Handle remaining 

A function can also re-throw a function using the same “throw; ” syntax. A function can handle a part and ask the caller to handle the remaining.

Property 6

When an exception is thrown, all objects created inside the enclosing try block are destroyed before the control is transferred to the catch block.

Example

The following program demonstrates the above property.

CPP
// C++ program to demonstrate

#include <iostream>
using namespace std;

// Define a class named Test
class Test {
public:
    // Constructor of Test
    Test() { cout << "Constructor of Test " << endl; }
    // Destructor of Test
    ~Test() { cout << "Destructor of Test " << endl; }
};

int main()
{
    try {
        // Create an object of class Test
        Test t1;

        // Throw an integer exception with value 10
        throw 10;
    }
    catch (int i) {
        // Catch and handle the integer exception
        cout << "Caught " << i << endl;
    }
}

Output
Constructor of Test 
Destructor of Test 
Caught 10

Limitations of Exception Handling in C++

The exception handling in C++ also have few limitations:

  • Exceptions may break the structure or flow of the code as multiple invisible exit points are created in the code which makes the code hard to read and debug.
  • If exception handling is not done properly can lead to resource leaks as well.
  • It’s hard to learn how to write Exception code that is safe.
  • There is no C++ standard on how to use exception handling, hence many variations in exception-handling practices exist.

Conclusion

Exception handling in C++ is used to handle unexpected happening using “try” and “catch” blocks to manage the problem efficiently. This exception handling makes our programs more reliable as errors at runtime can be handled separately and it also helps prevent the program from crashing and abrupt termination of the program when error is encountered.

Related Articles:



Previous Article
Next Article

Similar Reads

Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Exception Handling and Object Destruction in C++
An exception is termed as an unwanted error that arises during the runtime of the program. The practice of separating the anomaly-causing program/code from the rest of the program/code is known as Exception Handling. An object is termed as an instance of the class which has the same name as that of the class. A destructor is a member function of a
4 min read
C++ | Exception Handling | Question 1
#include <iostream> using namespace std; int main() { int x = -1; try { cout << "Inside try \n"; if (x < 0) { throw x; cout << "After throw \n"; } } catch (int x ) { cout << "Exception Caught \n"; } cout << "After catch \n"; return 0; } (A) Inside try Exception Caught After th
1 min read
C++ | Exception Handling | Question 3
What should be put in a try block? 1. Statements that might cause exceptions 2. Statements that should be skipped in case of an exception (A) Only 1 (B) Only 2 (C) Both 1 and 2 Answer: (C)Explanation: The statements which may cause problems are put in try block. Also, the statements which should not be executed after a problem occurred, are put in
1 min read
C++ | Exception Handling | Question 4
Output of following program #include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; try { throw d; } catch(Base b) { cout<<"Caught Base Exception"; } catch(Derived d) { cout<<"Caught Derived Exception"; } return 0; } (A) Caught Derived Exception (B) Caught B
1 min read
C++ | Exception Handling | Question 5
#include <iostream> using namespace std; int main() { try { throw 'a'; } catch (int param) { cout << "int exception\n"; } catch (...) { cout << "default exception\n"; } cout << "After Exception"; return 0; } (A) default exception After Exception (B) int exception After Exception (C) int exceptio
1 min read
C++ | Exception Handling | Question 6
#include <iostream> using namespace std; int main() { try { throw 10; } catch (...) { cout << "default exception\n"; } catch (int param) { cout << "int exception\n"; } return 0; } (A) default exception (B) int exception (C) Compiler Error Answer: (C) Explanation: It is compiler error to put catch all block befo
1 min read
C++ | Exception Handling | Question 7
#include <iostream> using namespace std; int main() { try { try { throw 20; } catch (int n) { cout << "Inner Catch\n"; throw; } } catch (int x) { cout << "Outer Catch\n"; } return 0; } (A) Outer Catch (B) Inner Catch (C) Inner Catch Outer Catch (D) Compiler Error Answer: (C) Explanation: The statement 'throw;'
1 min read
C++ | Exception Handling | Question 8
#include <iostream> using namespace std; class Test { public: Test() { cout << "Constructing an object of Test " << endl; } ~Test() { cout << "Destructing an object of Test " << endl; } }; int main() { try { Test t1; throw 10; } catch(int i) { cout << "Caught " << i << en
1 min read
C++ | Exception Handling | Question 9
#include <iostream> using namespace std; class Test { static int count; int id; public: Test() { count++; id = count; cout << "Constructing object number " << id << endl; if(id == 4) throw 4; } ~Test() { cout << "Destructing object number " << id << endl; } }; int Test::count = 0; int ma
2 min read
C++ | Exception Handling | Question 10
Which of the following is true about exception handling in C++? 1) There is a standard exception class like Exception class in Java. 2) All exceptions are unchecked in C++, i.e., compiler doesn't check if the exceptions are caught or not. 3) In C++, a function can specify the list of exceptions that it can throw using comma separated list like foll
1 min read
C++ | Exception Handling | Question 11
What happens in C++ when an exception is thrown and not caught anywhere like following program. #include <iostream> using namespace std; int fun() throw (int) { throw 10; } int main() { fun(); return 0; } (A) Compiler error (B) Abnormal program termination (C) Program doesn't print anything and terminates normally (D) None of the above Answer
1 min read
C++ | Exception Handling | Question 12
What happens when a function throws an error but doesn't specify it in the list of exceptions it can throw. For example, what is the output of following program? #include <iostream> using namespace std; // Ideally it should have been "int fun() (int)" int fun() { throw 10; } int main() { try { fun(); } catch (int ) { cout <<
1 min read
Python Exception Handling
We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4).  In this article, we will discuss how to handle exceptions in Python using try, except, and finally statements with the help of proper examples.  Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a program due to which
9 min read
Top C++ Exception Handling Interview Questions and Answers
Exception Handling is one of the most important topics from the C++ Interview perspective. Exception handling is an effective means to handle the runtime errors that disrupt the normal flow of the program. It is one of the most used concepts in real-world embedded systems so it is common to encounter questions based on exception handling during int
8 min read
Customizing termination behavior for uncaught exception In C++
Whenever an exception arises in C++, it is handled as per the behavior defined using the try-catch block. However, there is often the case when an exception is thrown but isn't caught because the exception handling subsystem fails to find a matching catch block for that particular exception. In that case, the following set of actions takes place: T
2 min read
exception::bad_exception in C++ with Examples
Standard C++ contains several built-in exception classes, exception::bad_exception is one of them. This is an exception thrown by unexpected handler. Below is the syntax for the same: Header File: include<exception> Syntax: class bad_exception; Return: The exception::bad_exception returns a null terminated character that is used to identify t
2 min read
exception::what() in C++ with Examples
The exception::what() used to get string identifying exception. This function returns a null terminated character sequence that may be used to identify the exception. Below is the syntax for the same: Header File: #include<exception> Syntax: virtual const char* what() const throw(); Return: The function std::what() return a null terminated ch
2 min read
Rethrowing an Exception in C++
Exception handling plays a role in developing robust software in C++. It offers a way to handle errors and unexpected situations. One interesting aspect of exception handling in C++ is the ability to rethrow an exception allowing it to pass up the call stack. Rethrowing an ExceptionRethrowing an exception in C++ involves catching an exception withi
5 min read
User-defined Custom Exception in Java
An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating
3 min read
Array Index Out Of Bounds Exception in Java
Java supports the creation and manipulation of arrays as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the JAVA throws an ArrayIndexOutOfBounds Exception. This
4 min read
Types of Exception in Java with Examples
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in excep
8 min read
C | File Handling | Question 1
Which of the following true about FILE *fp (A) FILE is a keyword in C for representing files and fp is a variable of FILE type. (B) FILE is a structure and fp is a pointer to the structure of FILE type (C) FILE is a stream (D) FILE is a buffered stream Answer: (B) Explanation: fp is a pointer of FILE type and FILE is a structure that store followin
1 min read
C | File Handling | Question 2
When fopen() is not able to open a file, it returns (A) EOF (B) NULL (C) Runtime Error (D) Compiler Dependent Answer: (B) Explanation: fopen() returns NULL if it is not able to open the given file due to any of the reasons like file not present, inappropriate permissions, etc.Quiz of this Question
1 min read
C | File Handling | Question 3
getc() returns EOF when (A) End of files is reached (B) When getc() fails to read a character (C) Both of the above (D) None of the above Answer: (C) Explanation: See EOF, getc() and feof() in CQuiz of this Question
1 min read
C | File Handling | Question 4
In fopen(), the open mode "wx" is sometimes preferred "w" because. 1) Use of wx is more efficient. 2) If w is used, old contents of file are erased and a new empty file is created. When wx is used, fopen() returns NULL if file already exists. (A) Only 1 (B) Only 2 (C) Both 1 and 2 (D) Neither 1 nor 2 Answer: (B) Explanation: See https://www.geeksfo
1 min read
C | File Handling | Question 5
fseek() should be preferred over rewind() mainly because (A) rewind() doesn't work for empty files (B) rewind() may fail for large files (C) In rewind, there is no way to check if the operations completed successfully (D) All of the above Answer: (C) Explanation: Please see fseek() vs rewind() in CQuiz of this Question
1 min read
Bank account system in C using File handling
This article focuses on how to create a bank account system using C language and File handling in C. Approach:Let's discuss the approach in detail, covering all the functions and their explanation in detail- Create a Menu in the main function and create different functions for the Menu, which will be called using switch case statements. There are f
12 min read
ATM using file handling in C++
In this article, the task is to implement an ATM with functions like add, delete, search, and update users using file handling in C++. File handling: File handling is used to store the output of a program in a file.In C++, files use three classes fstream, ifstream, ofstream available in fstream header file for file handling. Some Important Instruct
6 min read
Four File Handling Hacks which every C/C++ Programmer should know
We will discuss about four file hacks listed as below- Rename - Rename a file using C/C++Remove – Remove a file using C/C++File Size - Get the file size using C/C++Check existence – Check whether a file exists or not in C/C++ C/C++ Code // C++ Program to demonstrate the // four file hacks every C/C++ must know // Note that we are assuming that the
3 min read
Practice Tags :
three90RightbarBannerImg