VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-throw-an-exception-in-cpp/

⇱ How to Throw an Exception in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Throw an Exception in C++?

Last Updated : 23 Jul, 2025

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++.

Throw a C++ Exception

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. 

Syntax to Throw an Exception in C++

throw exception_object

Here, 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.

C++ Program to Throw an 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 error

Time Complexity: O(1)
Auxiliary Space: O(1)



Comment