C++ Exception Handling

  • Post author:
  • Post category:C++
  • Post comments:0 Comments

Exception Handling in C++

Exception handling is a powerful feature of C++ that allows us to handle errors in our programs. It allows us to write code that will detect and respond to errors in a controlled manner.

Let’s look at an example of exception handling in C++:

#include <iostream>
#include <exception>

int main()
        int x = 10;
        int y = 0;
        if (y == 0)
            throw std::exception("Division by zero!");
        int z = x / y;
    catch (std::exception &e)
        std::cout << e.what() << std::endl;
    return 0;


Division by zero!

In this example, we have used a try-catch block to check for a division by zero error. If the condition is true, the code will throw an exception with the message “Division by zero!”. The catch block will then catch the exception and print out the error message.

Leave a Reply