Exception Handling

Exception Handling

Exception Handling

Exception handling in C++ is a mechanism that allows you to handle runtime errors and other exceptional situations in your code. It is a way to gracefully recover from errors and continue executing your program, rather than crashing or producing incorrect results.

In C++, you can use the try, catch, and throw keywords to implement exception handling. Here’s an example:

				
					#include <iostream>
using namespace std;
int main() {
    try {
        int x = 10;
        int y = 0;
        if (y == 0) {
            throw "Divide by zero error";
        }
        int z = x / y;
        cout << "Result: " << z << endl;
    }
    catch (const char* msg) {
        cerr << "Error: " << msg << endl;
    }
    return 0;
}

				
			

In this example, we use the try keyword to enclose a block of code that might throw an exception. Inside this block, we declare and initialize two integer variables x and y. We then check if y is zero and throw an exception with an error message if it is.

If an exception is thrown, the program jumps to the nearest catch block that matches the type of the thrown exception. In this case, we catch the exception with a const char* parameter, which means that we catch exceptions of type const char*. Inside the catch block, we output an error message to the standard error stream.

If no exceptions are thrown, the program continues executing normally after the try block.

Note that you can catch different types of exceptions by specifying multiple catch blocks with different parameter types. You can also throw your own custom exception types by defining your own exception classes and throwing objects of those classes.

Top of Form

Using Throw

The throw keyword is used to throw an exception during program execution. It is typically used in conjunction with exception handling , which allows you to catch and handle these exceptions.

Here’s a simple example of how to use throw in C++:

				
					#include<iostream>

#include<string>

using namespace std;

int divide(int x, int y) {
    if (y == 0) {
        throw string("Divide by zero error");
    }

    return x / y;
}

int main() {

    try {

        int x = 10;
        int y = 0;
        int z = divide(x, y);
        cout << "Result: "<< z << endl;
    }

catch(string msg) {
        cerr << "Error: "<< msg << endl;
    }
    return 0;
}

​
				
			
Join To Get Our Newsletter
Spread the love