In C++, errors and exceptional situations can be handled using exceptions. An exception is an object that represents an error or an exceptional situation that occurs during program execution.
To throw an exception in C++, we use the `throw` keyword. For example:
void myFunction(int value) { if (value < 0) { throw std::invalid_argument("value must be positive"); } }
In this example, the `myFunction` function throws an `std::invalid_argument` exception if the `value` parameter is less than zero. The `std::invalid_argument` exception is a predefined exception type in C++ that represents an invalid argument error.
To catch an exception in C++, we use a `try-catch` block. For example:
try { myFunction(-1); } catch (const std::exception& e) { std::cerr << "An exception occurred: " << e.what() << std::endl; }
In this example, the `myFunction` function is called with an argument of `-1`, which will cause an exception to be thrown. The `try` block is used to wrap the function call, and the `catch` block catches any `std::exception` objects that are thrown. The `e.what()` function is used to retrieve the error message associated with the exception.
C++ also allows you to define your own exception classes by inheriting from the `std::exception`class or one of its derived classes. For example:
class MyException : public std::exception { public: virtual const char* what() const noexcept { return "MyException occurred"; } };
In this example, `MyException` is a custom exception class that inherits from `std::exception`. The `what()` function is overridden to return a custom error message.
To throw a custom exception in C++, you can create an instance of the exception class and throw it using the `throw` keyword. For example:
void myFunction(int value) { if (value < 0) { throw MyException(); } }
In this example, the `myFunction` function throws a `MyException` object if the `value` parameter is less than zero.
To catch a custom exception in C++, you can use a `catch` block that catches the custom exception type. For example:
try { myFunction(-1); } catch (const MyException& e) { std::cerr << "A MyException occurred: " << e.what() << std::endl; } catch (const std::exception& e) { std::cerr << "An exception occurred: " << e.what() << std::endl; }
In this example, the first `catch` block catches any `MyException` objects that are thrown, and the second `catch` block catches any other `std::exception` objects that are thrown.
It's important to handle exceptions properly in C++ to ensure that errors and exceptional situations are handled gracefully and don't cause program crashes or other unexpected behavior. It's also important to use exceptions judiciously and only for exceptional situations, as overuse of exceptions can lead to code that is harder to understand and maintain.