C++ is a language in which complex programs are made and compiled for different results. The language also includes some exception functions that you can follow to create codes. Exceptions allow programs to react to unusual circumstances (such as runtime errors) by delegating control to special functions known as handlers.

A section of code is placed under exception review, effectively capturing exceptions. It accomplishes this by enclosing the code in a try-block. When an unusual situation occurs within that block, it throws an exception and passes the control to the exception handler. The code continues normally if no exception is thrown, and it ignores all handlers. This tutorial explores exception handling in C++ using examples and multiple use cases for a more practical understanding.

What Is Exception Handling in C++? Explain With Example

A condition that occurs during the execution of a program is referred to as an exception. And exception handling in C++ is an answer to a rare occurrence that occurs during the execution of a program, such as an attempt to divide it by zero.

Exceptions enable power to be passed from one part of a program to another. The three keywords try, grab, and throw are used for exception handling in C++.

  • When a program encounters a problem, it throws an exception. The throw keyword is used to do this.
  • An error handler in a program catches an exception at the point in the program where you want to handle the problem. The catch keyword means that it caught an exception.
  • A try block designates a section of code for which specific exceptions will be raised. There are one or two capture blocks after it.

A method catches an exception by combining the try and catch keywords, assuming a block would raise an exception. A try/catch block is used to surround code that could throw an exception.

try {

   // protected code

} catch( Exception Name e1 ) {

   // catch block

} catch( Exception Name e2 ) {

   // catch block

} catch( Exception Name eN ) {

   // catch block

}

Why Is Exception Handling in C++ Used?

  • Separation of Error Handling and Normal Code: There are often if-else conditions to manage errors in typical error handling codes. These conditions, as well as the error-handling code, get mixed up in the usual flow. This makes the code more difficult to read and maintain. It separates the code for exception handling in C++ from the usual flow with try catch blocks.
  • Functions/methods can handle exceptions in whatever way they want: A function can choose to handle some of the exceptions it throws. The caller will handle all other deviations that are thrown but not caught. The caller exceptions are addressed by the caller if the caller tries not to catch them. The throw keyword, in exception handling in C++, allows a function to define the exceptions it would throw. This function's caller must treat the exception in some way.
  • Exceptions can be thrown in C++ for both basic types and artifacts. You can organize exception objects into a hierarchy, group them into namespaces or classes, and categorize them by category.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Throwing Exceptions in C++ - With an Example

When a method encounters an error, it produces an object and passes it to the runtime system. The object, known as an exception object, includes details about the error, such as its type and the program's state at the time of the error. Throwing exception handling in C++ is the process of creating an exception object and passing it to the runtime system.

When a process throws an exception, the runtime system looks for a way to deal with it. The ordered list of methods that are called, to get to the process where the error occurred is the collection of potential "somethings" to manage the exceptio.

Example

#include <iostream>

using namespace std;

double division(int a, int b) {

   if( b == 0 ) {

   throw "Division by zero condition!";

   }

   return (a/b);

int main () {

   int x = 50;

   int y = 0;

   double z = 0; 

   try {

   z = division(x, y);

   cout << z << endl;

   } catch (const char* msg) {

  cerr << msg << endl;

   }

   return 0;

}

Output:

Exception_Handling_In_C_Plus_Plus_1

Catching Exceptions 

A major part of exception handling in C++ is catching them in time. Exceptions are issues that occur during the execution of a program. It is an occurrence that occurs during the execution of a program. And after throwing an exception, it protects the code and runs the application. You can handle the exceptions using exception management. To protect the code, you can use the try catch block.

Both forms of exceptions are caught using the catch block. Exceptions are caught using the keyword catch. In the C++ language, here's an example of capturing all exceptions:

Example: 

#include <iostream>

using namespace std;

void func(int a) {

   try {

      if(a==0) throw 23.33;

      if(a==1) throw 's';

   } catch(...) {

      cout << "Caught Exception!\n";

   }

}

int main() {

   func(0);

   func(1);

   return 0;

}

Output:

Exception_Handling_In_C_Plus_Plus_2

How to Define New Exceptions?

Exception handling in C++ also leads to finding new exceptions. When something goes wrong in a try catch block, it throws an exception automatically. The flung elements are caught by the grab blocks. Throws automatically guide the runtime to the stack's closest catch block. You usually use a lot of throws and a few catches.

  • Make a new class with a name that ends in Exception, such as ClassNameException. This is a convention for distinguishing between exceptions and normal classes.
  • Make the class extend one of the java.lang.Exception class's exceptions, which are subtypes. A custom exception class is almost always derived directly from the Exception class.
  • Create a function Object() { [native code] } with a string parameter that contains the exception's detail message. 
  • Simply call the super function Object() { [native code] } and transfer the message in this function Object() { [native code] }.

Example

public class StudentNotFoundException extends Exception {

    public StudentNotFoundException(String message) {

        super(message);

    }

}

public class StudentManager {

     public Student find(String studentID) throws StudentNotFoundException {

        if (studentID.equals("123456")) {

            return new Student();

        } else {

            throw new StudentNotFoundException(

                "Could not find student with ID " + studentID);

        }

    }

}

public class StudentTest {

    public static void main(String[] args) {

        StudentManager manager = new StudentManager();

        try {

            Student student = manager.find("0000001");

        } catch (StudentNotFoundException ex) {

            System.err.print(ex);

        }

    }

}

Output

Exception_Handling_In_C_Plus_Plus_3.

Example: 

#include <iostream>

#include<conio.h>

using namespace std;

int main()

{

int x[3] = {-1,2};

for(int i=0; i<2; i++)

{

     int ex = x[i];

     try

     {

         if (ex > 0)

             // throwing numeric value as exception

             throw ex;

         else

             // throwing a character as exception

             throw 'ex';

     }

     catch (int ex)  // to catch numeric exceptions

     {

         cout << "Integer exception\n";

     }

     catch (char ex) // to catch character/string exceptions

     {

         cout << "Character exception\n";

     }

}

}

Output

Exception_Handling_In_C_Plus_Plus_4

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Are Standard Exceptions in C++?

In C++, you can use the exception> keyword to create some regular exceptions that you can use in your programs. While exception handling in C++, it is critical to know these standard exceptions and know how to manage them. These standard exceptions are organized into a parent-child class hierarchy, as seen below:

  • Std::exception - It is the base class for all C++ exceptions.
  • Logical error - An exception occurs in a program's internal logic.
  • Domain error - An exception has occurred as a result of the use of an invalid domain.
  • Invalid argument - An exception has occurred as a result of an invalid argument.
  • Size requirement exceeds allocation - Exception due to size requirement exceeding the allocation.
  • Length error - An exception has been thrown due to a length error.
  • Runtime error - An exception occurs when the program is running.
  • Range error - Error in internal computations due to range errors.
  • Overflow error - Error caused by arithmetic overflow.
  • Underflow error - Exception due to arithmetic underflow errors
  • When memory allocation with new() fails, an exception is thrown called bad_alloc.
  • When a dynamic_cast fails, a bad cast exception is thrown.
  • bad exception - This exception was created specifically for use in the dynamic-exception-specifier.
  • typeid throws a bad typeid exception.
Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

This pretty much sums up exception handling in C++. There are a lot of things that you can do with this function. Want to learn about these in detail? Then you can get yourself placed in the best course by Simplilearn and become a full stack developer. 

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, at the earliest.

Happy learning!