Exception Handling

An exception is an unexpected event that occurs during program execution. For example,

divide_by_zero = 5 / 0;

The above code causes an exception as it is not possible to divide a number by 0.

The process of handling these types of errors in C++ is known as exception handling.

 

C++ provides three primary keywords for handling exceptions:

 1.try – Defines a block of code that might throw an exception.

 2.catch – Handles the exception thrown from the try block.

 3. throw – Used to throw an exception.

 

The basic syntax for exception handling in C++ is given below:

 try {

 

    // code that may raise an exception

    throw argument;

}

 

catch (exception) {

    // code to handle exception

}

 

Arithmetic Errors

Errors that occur due to mathematical operations, such as:

  • Division by zero
  • Integer overflow or underflow

 

 Example:

#include <iostream>

using namespace std;

 

int main() {

    int numerator, denominator;

 

    cout << "Enter numerator: ";

    cin >> numerator;

 

    cout << "Enter denominator: ";

    cin >> denominator;

 

    try {

        if (denominator == 0) {

            throw "Division by zero is not allowed!";

        }

        cout << "Result: " << (numerator / denominator) << endl;

    }

    catch (const char*  errorMessage) {

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

    }

 

    cout << "Program continues normally..." << endl;

    return 0;

}

 

 

 

#include <iostream>

using namespace std;

 

int main() {

    //unsigned int num = 4294967295; // Max value for unsigned int (32-bit)

    int num = 32768;

    cout << "Number: " << num << endl;

 

    // Overflow (adding 1 to max value)

    num = num + 1;

    cout << "After Overflow: " << num << endl;

 

    // Underflow (subtracting 1 from 0)

    num = 0;

    num = num - 1;

    cout << "After Underflow: " << num << endl;

 

    return 0;

}

 

No comments:

Post a Comment