Exception Handling in C++

 Exception Handling in C++


Exception handling is a way to gracefully handle errors and unexpected conditions in a program. In C++, you can use try and catch blocks to handle exceptions. Here's an example of using exception handling in C++:


c++


#include <iostream>


int main() {

  try {

    int x = 10;

    int y = 0;

    int z = x / y;

  } catch (const std::exception& e) {

    std::cerr << "Error: " << e.what() << std::endl;

  }


  return 0;

}

In this example, we're attempting to divide 10 by 0, which would normally cause a runtime error. However, we've wrapped this code in a try block and provided a catch block to handle any exceptions that might be thrown. In this case, we're catching a std::exception and printing out the error message using cerr.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...