Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Sunday, September 29, 2024

Exception Handling

 Exception Handling

 Exception Handling in C++ is a mechanism that allows a program to handle runtime errors or exceptions gracefully, ensuring that the program can continue executing or terminate cleanly without crashing. This is done using a combination of the try, catch, and throw keywords.

Key Concepts in Exception Handling

  1. Exception: An event that disrupts the normal flow of a program's execution. This can be caused by various factors, such as invalid input, resource unavailability, etc.

  2. Try Block: The block of code where exceptions may occur. If an exception is thrown within this block, it is handled in the corresponding catch block.

  3. Catch Block: A block that handles the exception. You can have multiple catch blocks to handle different types of exceptions.

  4. Throw Statement: Used to signal that an exception has occurred. When an exception is thrown, control is transferred to the catch block that matches the exception type.


Basic Syntax of Exception Handling

try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Code that handles the exception
}

Example of Exception Handling

#include <iostream>
#include <stdexcept> // Include for standard exceptions
using namespace std;

double divide(int numerator, int denominator) {
    if (denominator == 0) {
        throw invalid_argument("Denominator cannot be zero."); // Throw an exception
    }
    return static_cast<double>(numerator) / denominator; // Return division result
}
int main() {
    int num1, num2;
    
    cout << "Enter numerator: ";
    cin >> num1;
    cout << "Enter denominator: ";
    cin >> num2;
    try {
        double result = divide(num1, num2); // Try to divide
        cout << "Result: " << result << endl;
    } catch (const invalid_argument& e) { // Catch the specific exception
        cout << "Error: " << e.what() << endl; // Handle the exception
    } catch (...) { // Catch-all for any other exceptions
        cout << "An unknown error occurred." << endl;
    }
    return 0;
}


Explanation:

  1. Divide Function:

    • The divide function takes two integers as input.
    • If the denominator is zero, it throws an invalid_argument exception.
  2. Main Function:

    • Prompts the user to input numerator and denominator.
    • It calls the divide function inside a try block.
    • If an exception is thrown, control is transferred to the corresponding catch block.
  3. Catch Blocks:

    • The first catch block catches the invalid_argument exception and displays an error message.
    • The second catch block (catch(...)) is a catch-all for any other exceptions that may occur.

Advantages of Exception Handling

  1. Separation of Error Handling from Regular Code: Keeps the error handling code separate from the main logic, making the code cleaner and easier to read.

  2. Propagating Errors: Exceptions can propagate up the call stack until they are caught, allowing higher-level functions to handle errors.

  3. Resource Management: Exceptions provide a way to handle resource management and cleanup tasks reliably using destructors or smart pointers.


Summary

  • Exception handling in C++ is a powerful mechanism for managing errors during runtime.
  • It consists of try, catch, and throw statements to handle exceptions in a structured manner.
  • By using exception handling, you can build robust applications that can deal with unexpected situations without crashing, improving the overall reliability of your programs.

No comments:

Post a Comment