CPP Exception Handling

Exception Handling in C++ Programming Language

In the realm of programming, an exception is a situation that arises during the execution of a program, indicating an abnormal condition.

B">C++ exceptions are responses to extraordinary circumstances that occur while a program is running. These circumstances might include attempting to divide by zero or accessing memory that hasn’t been allocated. we will take a deep dive into C++ exception handling, exploring how to effectively manage errors and unexpected situations in your code.

Exception handling in C++ is built on three fundamental keywords: try, catch, and throw. Each of these keywords plays a distinct role in managing exceptions and ensuring your program can gracefully handle unexpected scenarios.

1. throw: When a problem arises, a program can throw an exception to indicate that something has gone wrong. The throw keyword is used to initiate this process.

2. catch: A program catches an exception using an exception handler placed at the specific location where you want to address the issue. The catch keyword marks the section of code where an exception can be handled.

3. try: A try block identifies a segment of code that might raise exceptions. It is followed by one or more catch blocks, each designed to handle a specific type of exception.

When you anticipate that a block of code might generate an exception, you wrap it within a try block. The code within this block is referred to as protected code. The syntax for employing try and catch looks like this:

try {
   // protected code
} catch(ExceptionType e1) {
   // catch block
} catch(ExceptionType e2) {
   // catch block
} catch(ExceptionType eN) {
   // catch block
}

You can include multiple catch statements to handle different types of exceptions that may arise in various situations.

Throwing Exceptions

Exceptions can be thrown anywhere within a code block using the throw statement. The operand of the throw statement determines the type of the exception. It can be any expression, and the type of the result of that expression becomes the type of the thrown exception. Consider this example:

double division(int a, int b) {
   if (b == 0) {
      throw "Division by zero condition!";
   }
   return (a / b);
}

Catching Exceptions

A catch block following a try block catches any thrown exception. You can specify the type of exception you want to catch by declaring the exception type in the parentheses following the catch keyword. If you want to catch any type of exception, you can use ... (ellipsis) as the parameter.

try {
   // protected code
} catch(ExceptionType e) {
  // code to handle ExceptionType exception
}

If you use ..., the catch block will handle any exception type thrown within the try block.

Here’s an example where we throw a division by zero exception and catch it in a catch block:

#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;
}

By embracing C++’s exception handling mechanism, you can effectively manage unexpected situations in your code. The combination of try, catch, and throw enables you to gracefully handle exceptional circumstances, ensuring your program remains robust and user-friendly.

C++ Standard Exceptions

C++ provides a set of standard exceptions defined in the <exception> header. These exceptions are organized in a hierarchy. Some of the commonly used ones include std::bad_alloc for memory allocation failure, std::invalid_argument for invalid function arguments, std::runtime_error for general runtime errors, and more.

Defining Custom Exceptions

You have the flexibility to define your own exceptions by inheriting and overriding the functionality of the std::exception class. Here’s a demonstration of how you can create a custom exception using the std::exception class:

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

struct MyException : public exception {
   const char* what() const throw() {
      return "C++ Exception";
   }
};

int main() {
   try {
      throw MyException();
   } catch (MyException& e) {
      cout << "MyException caught" << endl;
      cout << e.what() << endl;
   } catch (exception& e) {
      // Handle other errors
   }
}

In this example, the what() method, inherited from std::exception, returns the cause of the exception. By creating your custom exceptions, you can tailor your program’s error handling to specific situations.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading