Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Exception Handling

Introduction

Exception handling is a way to manage and respond to errors that occur during the execution of a program. It helps your program deal with unexpected situations without crashing, by allowing it to handle errors gracefully.

Key Concepts:

  1. Exception: An object representing an error or unusual condition in the program.

2. Throwing an Exception: When an error occurs, you use the throw keyword to create and “throw” an exception. This transfers control to a special section of code that handles errors.

3. Catching an Exception: You use try and catch blocks to manage exceptions:

  • try Block: Contains code that might throw an exception.
  • catch Block: Contains code to handle the exception if it occurs.

4. Custom Exceptions: You can create your own types of exceptions by defining custom exception classes.

For example:

Imagine you are writing a program to divide two numbers. If the denominator is zero, dividing by zero is an error. Exception handling lets you manage this error gracefully.

#include <iostream>
using namespace std;

// Function to divide two numbers
double divide(double numerator, double denominator) {
    if (denominator == 0) {
        throw "Division by zero error"; // Throwing an exception
    }
    return numerator / denominator;
}

int main() {
    double num = 10;
    double den = 0;
    
    try {
        // Try to perform the division
        double result = divide(num, den);
        cout << "Result: " << result << endl;
    } catch (const char* errorMessage) {
        // Handle the exception
        cout << "Error: " << errorMessage << endl;
    }

    return 0;
}

Output:

ERROR!
Error: Division by zero error

Explanation:

Step1: Function to Divide:

  • The divide function attempts to divide two numbers. If the denominator is zero, it throws an exception with the message "Division by zero error".
double divide(double numerator, double denominator) {
    if (denominator == 0) {
        throw "Division by zero error"; // Throwing an exception
    }
    return numerator / denominator;
}

Step 2: Handling Exceptions in main():

  • The try block contains code that might throw an exception. In this case, it calls the divide function.
  • The catch block catches exceptions of type const char* (the type of exception we threw) and prints the error message.
int main() {
    double num = 10;
    double den = 0;
    
    try {
        double result = divide(num, den);
        cout << "Result: " << result << endl;
    } catch (const char* errorMessage) {
        cout << "Error: " << errorMessage << endl;
    }

    return 0;
}

    Leave a Reply

    Your email address will not be published.

    Need Help?