C++ Exceptions
C++ Exceptions are a mechanism in C++ programming to handle runtime errors, such as division by zero, array out of bounds, and others, during the execution of a program. The advantage of exceptions is that they allow the program to continue running after an error has occurred, instead of immediately terminating the program. This provides a cleaner way to handle errors and can make it easier to diagnose and resolve problems.
In C++, exceptions are thrown by using the "throw" keyword, followed by the value or object representing the exception. The exception is then caught by using a "try" block, followed by a "catch" block. The "try" block specifies the code that may throw an exception, and the "catch" block specifies the code that will be executed if an exception is thrown.
Here's a simple example that demonstrates how exceptions work in C++:
1#include <iostream> 2using namespace std; 3 4int divide(int a, int b) { 5 if (b == 0) { 6 throw "Cannot divide by zero."; 7 } 8 return a / b; 9} 10 11int main() { 12 int x, y; 13 cout << "Enter two numbers: "; 14 cin >> x >> y; 15 16 try { 17 int result = divide(x, y); 18 cout << "Result: " << result << endl; 19 } catch (const char* msg) { 20 cerr << msg << endl; 21 } 22 23 return 0; 24}
In this example, the function "divide" takes two integers as inputs and returns their division result. If the second input is zero, the function throws an exception with a message "Cannot divide by zero.". In the main function, the "try" block contains the call to the "divide" function, and the "catch" block contains the code to handle the exception. If the exception is thrown, the message is printed using the "cerr" stream, which is used for error output.
Here's the output of this program when a non-zero value is entered for the second number:
1Enter two numbers: 4 2 2Result: 2
And here's the output when zero is entered for the second number:
1Enter two numbers: 4 0 2Cannot divide by zero.
As you can see, in the first case, the program correctly calculates the division result, and in the second case, the program correctly handles the exception by printing the error message.