![]() |
VOOZH | about |
In C++, exception handling is a mechanism that allows us to handle runtime errors and exceptions are objects that represent an error that occurs during the execution of a program. In this article, we will learn how to throw an exception in C++.
Throwing an exception means sending the exception to the catch block after it has occurred in the program. To throw an exception in C++, we can use thethrow keyword followed by an instance of the exception. When a program encounters a throw statement, then it immediately terminates the current function and starts finding a matching catch block to handle the thrown exception. Generally throw is used inside atry block or a function that is called within a try block.
throw exception_objectHere, exception_object is typically an instance of an exception class that can be a built-in type (like int or const char*), but more commonly, we use a class derived from std::exception.
The following program illustrates how we can throw an exception in case of divide by zero runtime error in C++.
Output
Exception caught: Division by zero errorTime Complexity: O(1)
Auxiliary Space: O(1)