VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-throw-and-catch-exceptions-in-cpp/

⇱ How to Throw and Catch Exceptions in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Throw and Catch Exceptions in C++?

Last Updated : 23 Jul, 2025

In C++, exception handling is a mechanism that allows us to handle runtime errors and exceptions are unusual conditions that occur at runtime. In this article, we will learn how to throw and catch exceptions in C++.

Throw and Catch Exceptions in C++

In C++ exceptions can be "thrown" when an error occurs and can be "caught" and "handled" to ensure the program's flow remains uninterrupted.

Throwing Exceptions in C++

We can use the throw keyword to throw an exception followed by an exception object from inside a try block. As soon as a program encounters a throw statement it immediately terminates the current function and starts finding a matching catch block to handle the thrown exception.

Catching Exceptions in C++

To catch an exception, we can use the catchkeyword. The catch block follows the try block and is used to handle any exceptions that are thrown within the try block.

Syntax to Throw and Catch Exceptions in C++

try {
 // Code that might throw an exception
  throw exception_object;
}
catch (exception_type e) {
 //catch the exception thrown from try block and handle it
}

Here, exception_object is an instance of an exception class, and exception_type is the type of exception that the catch block can handle.

C++ Program to Throw and Catch Exception

The following program illustrates how we can throw and catch an exception in C++.


Output

Caught exception: Division by zero error

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



Comment