Exception Handling

An example demonstrating how to handle exceptions in C++.

cppCopy code#include <iostream>
#include <stdexcept>

double divide(int a, int b) {
if (b == 0) {
    throw std::invalid_argument("Division by zero!");
}
return static_cast&lt;double&gt;(a) / b;
} int main() {
try {
    std::cout &lt;&lt; divide(10, 2) &lt;&lt; std::endl; // Output: 5
    std::cout &lt;&lt; divide(10, 0) &lt;&lt; std::endl; // This will throw an exception
} catch (const std::invalid_argument&amp; e) {
    std::cerr &lt;&lt; "Error: " &lt;&lt; e.what() &lt;&lt; std::endl;
}
return 0;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *