How to set a variable to a value or null if there is an exception in cpp ?
- User
How to set a variable to a value or null if there is an exception in cpp ?
- Assistant
In C++, you can use try-catch blocks to handle exceptions and set a variable to a value or null in case of an exception. Here is an example:
cpp#include <iostream> #include <string> int main() { int value; try { // Code that might throw an exception value = std::stoi("123"); // String to integer conversion } catch (const std::exception& e) { // Exception occurred value = 0; // Set value to a default value or null } std::cout << "Value: " << value << std::endl; return 0; }In this example, we attempt to convert the string "123" to an integer using the
std::stoifunction. If the conversion is successful, the value is assigned to thevaluevariable. However, if an exception occurs during the conversion (for example, if the given string cannot be converted to an integer), the catch block will be executed, and we can set the value to 0 or any other desired default value.