Instagram
youtube
Facebook
Twitter

Exception Handling

Exception Handling:

Exception handling is a programming mechanism that allows developers to manage and handle unanticipated or exceptional situations that may occur during the execution of a program. These exceptional situations, known as exceptions, can include errors, invalid inputs, resource unavailability, or any other unanticipated behaviour that disrupts the normal flow of the program.

The purpose of exception handling is to:

Separate error handling from regular code. Exception handling allows developers to separate error-handling code from the normal flow of the program. This enhances code readability and maintainability.

Graceful Recovery When an exception occurs, the program can gracefully recover from the error and continue its execution rather than abruptly terminating.

Error Reporting Exception handling provides a structured way to report and log errors, making diagnosing and fixing issues easier.

The introductory components of exception handling generally include:

  • Throwing an Exception: When an exceptional situation occurs, the program raises an exception by using the ‘throw’ statement. The throw statement generally takes an object representing the exception, which can be of any type, including built-in types or custom exception classes.

 

#include <iostream>

#include <stdexcept>

int divide(int a, int b) {

    if (b == 0) {

        throw std::runtime_error("Division by zero!");

    }

    return a / b;

}
 
int main() {

    try {

        int result = divide(10, 0);

        std::cout << "Result: " << result << std::endl;

    } catch (const std::exception& e) {

        std::cerr << "Error: " << e.what() << std::endl;

    }

    return 0;

}

 

  • Catching an Exception: To handle exceptions, the program uses try-and-catch blocks. The code that may raise an exception is placed inside a try block. However, the program searches for a corresponding catch block that can handle that type of exception. If an exception is thrown within the try block.

 

try { 

} catch (ExceptionType1& e1) {

} catch (ExceptionType2& e2) {

} catch (...) {

}

 

  • Handling the Exception: The catch block is responsible for handling the exception. It specifies the type of exception it can handle and the code to be executed if that exception is thrown. Multiple catch blocks can be used to handle different types of exceptions.

 

class MyException : public std::exception {

public:

    const char* what() const noexcept override {

        return "This is a custom exception.";

    }

};

void myFunction() {

    throw MyException();

}

 

  • Finally Block (optional): Optionally, you can include a final block that is executed regardless of whether an exception is thrown or caught. It’s frequently used to release resources or perform cleanup tasks.

illustration in C++ 

#include <iostream>

using namespace std;

int divide(int a, int b) {

if (b == 0) {

throw "Division by zero is not allowed!";

}

return a / b;

}

int main() {

int num1, num2;

cout << "Enter two numbers: ";

cin >> num1 >> num2;


try {

int result = divide(num1, num2);

cout << "Result of division: " << result << endl;

} catch (const char* errorMessage) {

cout << "Error: " << errorMessage << endl;

} catch (...) {

cout << "Unknown exception occurred." << endl;

} return 0; 

}

In this C++ illustration, the divide function throws an exception if the alternate argument b is zero. The try block in the main function attempts to call divide with user-provided values. However, the corresponding catch block is executed to handle the exception. If one occurs.

Exception handling is an important mechanism for dealing with unanticipated situations in a program, making code more robust and

dependable. Still, it should be used judiciously, and exceptions should be used only for exceptional cases and not as a regular control flow mechanism.