---
description: What is Exception Handling in C++? Exception handling in C++ provides you with a way of handling unexpected circumstances like runtime errors. So whenever an unexpected circumstance occurs, the progr
title: C++ Exception Handling: Try, Catch, throw Example
image: https://www.guru99.com/images/cpp-exception-handling.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Exception handling in C++ lets a program detect and respond to runtime errors using try, catch, and throw, so it does not crash. Here you will learn the keywords, syntax, standard exceptions, and user-defined exceptions with examples.

* ⚠️ **What it is:** Exception handling catches runtime errors so a program can recover.
* 🔑 **Keywords:** It uses try to test code, throw to raise, and catch to handle errors.
* 🧾 **Syntax:** Put risky code in a try block and handle errors in catch blocks.
* 📚 **Standard exceptions:** C++ provides built-in exceptions in the exception header.
* 🤖 **AI help:** AI tools like GitHub Copilot add try-catch blocks and error handling.

[ Read More ](javascript:void%280%29;) 

![C++ Exception Handling](https://www.guru99.com/images/cpp-exception-handling.png)

## What is Exception Handling in C++?

Exception handling in C++ provides you with a way of handling unexpected circumstances like runtime errors. So whenever an unexpected circumstance occurs, the program control is transferred to special functions known as handlers.

To catch the exceptions, you place some section of code under exception inspection. The section of code is placed within the try-catch block.

If an exceptional situation occurs within that section of code, an exception will be thrown. Next, the exception handler will take over control of the program.

In case no exceptional circumstance occurs, the code will execute normally. The handlers will be ignored.

In this C++ tutorial, you will learn:

## Why Exception Handling?

Here, are the reason for using Exception Handling in C++:

* You will separate your error handling code from your normal code. The code will be more readable and easier to maintain.
* Functions can handle the exceptions they choose. Even if a function throws many exceptions, it will only handle some. The caller will handle the uncaught exceptions.

## Exception Handling Keywords

Exception handling in C++ revolves around these three keywords:

* **throw**– when a program encounters a problem, it throws an exception. The throw keyword helps the program perform the throw.
* **catch**– a program uses an exception handler to catch an exception. It is added to the section of a program where you need to handle the problem. It’s done using the catch keyword.
* **try**– the try block identifies the code block for which certain exceptions will be activated. It should be followed by one/more catch blocks.

Suppose a code block will raise an exception. The exception will be caught by a method using try and catch keywords. The try/catch block should surround code that may throw an exception. Such code is known as protected code.

## Syntax

The try/catch takes this syntax:

try {
   // the protected code
} catch( Exception_Name exception1 ) {
   // catch block
} catch( Exception_Name exception2 ) {
   // catch block
} catch( Exception_Name exceptionN ) {
   // catch block
}

* Although we have one try statement, we can have many catch statements.
* The ExceptionName is the name of the exception to be caught.
* The exception1, exception2, and exceptionN are your defined names for referring to the exceptions.

### Example 1:

#include<iostream>
#include<vector>
using namespace std;

int main() {
	vector<int> vec;
	vec.push_back(0);	
	vec.push_back(1);	
	// access the third element, which doesn't exist
	try
	{
		vec.at(2);		
	}
	catch (exception& ex)
	{
		cout << "Exception occurred!" << endl;
	}
	return 0;
}

**Output:**

[](https://www.guru99.com/images/2/062620%5F0724%5FCExceptionH1.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/062620%5F0724%5FCExceptionH2.png)

**Code Explanation:**

1. Include the iostream header file in the program to use its [functions](https://www.guru99.com/cpp-functions.html).
2. Include the vector header file in the program to use its functions.
3. Include the std namespace in the program to its classes without calling it.
4. Call the main() function. The program logic should be added within its body.
5. Create a vector named vec to store integer data.
6. Add the element 0 to the vector named vec.
7. Add the element 1 to the vector named vec.
8. A comment. It will be skipped by the [C++ compiler](https://www.guru99.com/best-cpp-ide-editor-free.html).
9. Use the try statement to catch an exception. The { marks the beginning of the body of try/catch block. The code added within the body will become the protected code.
10. Try to access the element stored at index 2 (third element) of the vector named vec. This element doesn’t exist.
11. End of the body of try/catch block.
12. Catch the exception. The returned error message will be stored in the variable ex.
13. Print out some message on the console if the exception is caught.
14. End of the body of the catch block.
15. The program should return a value upon successful execution.
16. End of the main() function body.

### RELATED ARTICLES

* [What is C++? Basic Concepts of C++ Programming Language ](https://www.guru99.com/cpp-tutorial.html "What is C++? Basic Concepts of C++ Programming Language")
* [Arrays in C++: Declare, Initialize & Pointers (Examples) ](https://www.guru99.com/arrays-in-cpp-functions.html "Arrays in C++: Declare, Initialize & Pointers (Examples)")
* [C++ Dynamic Allocation of Arrays with Example ](https://www.guru99.com/cpp-dynamic-array.html "C++ Dynamic Allocation of Arrays with Example")
* [C++ Functions with Program Examples ](https://www.guru99.com/cpp-functions.html "C++ Functions with Program Examples")

### Example 2:

#include <iostream>
using namespace std;
double zeroDivision(int x, int y) {

	if (y == 0) {
		throw "Division by Zero!";
	}
	return (x / y);
}

int main() {
	int a = 11;
	int b = 0;
	double c = 0;

	try {
		c = zeroDivision(a, b);
		cout << c << endl;
	}
	catch (const char* message) {
		cerr << message << endl;
	}
	return 0;
}

**Output:**

[](https://www.guru99.com/images/2/062620%5F0724%5FCExceptionH3.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/062620%5F0724%5FCExceptionH4.png)

**Code Explanation:**

1. Include the iostream header file in the program to use its functions.
2. Include the std namespace in the program to its classes without calling it.
3. Create a function named zeroDivision that takes two integer arguments, x, and y. The function should return a double result.
4. Use an if statement to check whether the value of variable argument y is 0\. The { marks the beginning of if body.
5. The message to be returned/thrown if y is 0.
6. End of the body of the if statement.
7. The zeroDivision function should return the value of x/y.
8. End of the body of the zeroDivision function.
9. Call the main() method. The { marks the beginning of this method.
10. Declare an integer variable and assigning it the value 11.
11. Declare an integer variable b and assigning it the value 0.
12. Declare a double variable c and assigning it the value 0.
13. Use the try statement to catch an exception. The { marks the beginning of the body of try/catch block. The code added within the body will become the protected code.
14. Call the zeroDivision function and passing to arguments a and b, that is, 11 and 0\. The result of this operation will be stored in variable c.
15. Print out the value of variable c on the console.
16. End of the body of try/catch block.
17. Catch the exception. The returned error message will be stored in the variable message.
18. Print out the returned error message on the console.
19. End of the body of the catch block.
20. The program should return a value upon successful execution.
21. End of the main() function body.

## C++ Standard Exceptions

[](https://www.guru99.com/images/2/062620%5F0724%5FCExceptionH5.png)

C++ comes with a list of standard exceptions defined in <exception> class. These are described below:

| Exception              | Description                                                               |
| ---------------------- | ------------------------------------------------------------------------- |
| std::exception         | This is an exception and the parent class of all standard C++ exceptions. |
| std::bad\_alloc        | This exception is thrown by a new keyword.                                |
| std::bad\_cast         | This is an exception thrown by dynamic\_cast.                             |
| std::bad\_exception    | A useful device for handling unexpected exceptions in C++ programs.       |
| std::bad\_typeid       | An exception thrown by typeid.                                            |
| std::logic\_error      | This exception is theoretically detectable by reading code.               |
| std::domain\_error     | This is an exception thrown after using a mathematically invalid domain.  |
| std::invalid\_argument | An exception thrown for using invalid arguments.                          |
| std::length\_error     | An exception thrown after creating a big std::string.                     |
| std::out\_of\_range    | Thrown by at method.                                                      |
| std::runtime\_error    | This is an exception that cannot be detected via reading the code.        |
| std::overflow\_error   | This exception is thrown after the occurrence of a mathematical overflow. |
| std::range\_error      | This exception is thrown when you attempt to store an out-of-range value. |
| std::underflow\_error  | An exception thrown after the occurrence of mathematical underflow.       |

## User-Defined Exceptions

The C++ std::exception class allows us to define objects that can be thrown as exceptions. This class has been defined in the <exception> header. The class provides us with a virtual member function named what.

This function returns a null-terminated character sequence of type char \*. We can overwrite it in derived classes to have an exception description.

### Example:

#include <iostream>
#include <exception>
using namespace std;

class newException : public exception
{
	virtual const char* what() const throw()
	{
		return "newException occurred";
	}
} newex;

int main() {

	try {
		throw newex;
		}
	catch (exception& ex) {
		cout << ex.what() << '\n';
	}
	return 0;	
}

**Output:**

[](https://www.guru99.com/images/2/062620%5F0724%5FCExceptionH6.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/062620%5F0724%5FCExceptionH7.png)

**Code Explanation:**

1. Include the iostream header file in our program. We will use its functions without getting errors.
2. Include the exception header file in our program. We will use its functions like what without errors.
3. Include the std namespace in our program to use its classes without calling it.
4. Create a new class named newException. This class inherits the exception class of C++.
5. The beginning of the class body.
6. Overwrite the virtual member function what() defined in the exception header file. We will then describe our own exception, the new exception.
7. Start the definition of the new exception.
8. The message to be returned if the new exception is caught.
9. End of the definition of the new exception.
10. End of the body of class newException. The newex is the name to be used to catch our new exception, after which the newException will be called.
11. Call the main() function. The program logic should be added within its body. The { marks the beginning of its body.
12. Use a try statement to mark the code within which we need to mark the exception. The { marks the beginning of the body of try/catch block. The code surrounded by this will become protected.
13. Throw the newex exception if it’s caught.
14. End of the try body.
15. Use the catch statement to catch the exception. The exception error message will be stored in variable ex.
16. Print the exception error message on the console.
17. End of the body of catch statement.
18. The program should return a value if it executes successfully.
19. End of the body of the main() function.

## FAQs

⚠️ What is exception handling in C++?

Exception handling is a way to detect and respond to runtime errors in C++ using the try, throw, and catch keywords, so the program can recover instead of crashing.

🔑 What are the exception handling keywords in C++?

C++ uses three keywords: try wraps code that might fail, throw raises an exception when an error occurs, and catch handles the thrown exception.

🧾 What is the syntax of try-catch in C++?

Place risky code in a try block, then follow it with one or more catch blocks that each handle a specific exception type thrown from the try block.

📚 What are standard exceptions in C++?

Standard exceptions are built-in exception classes in the exception header, such as std::bad\_alloc and std::out\_of\_range, that report common runtime errors.

🛠️ What is a user-defined exception in C++?

A user-defined exception is a custom class, often derived from std::exception, that overrides the what() function to describe your own specific error condition.

🤖 How can AI tools like GitHub Copilot help with exception handling?

AI assistants like GitHub Copilot wrap risky code in try-catch blocks, generate custom exception classes, and suggest which exceptions to catch as you type.

🧠 Can AI improve error handling in C++?

Yes. AI-powered tools spot unhandled exceptions, suggest specific catch blocks over generic ones, and add meaningful error messages, making your C++ code more robust.

🆚 What is the difference between throw and catch?

throw raises an exception when an error is detected, while catch receives that exception and runs the code that handles or reports the error.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/cpp-exception-handling.png","url":"https://www.guru99.com/images/cpp-exception-handling.png","width":"700","height":"250","caption":"C++ Exception Handling","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/cpp-exceptions-handling.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/cpp","name":"CPP"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/cpp-exceptions-handling.html","name":"C++ Exception Handling: Try, Catch, throw Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/cpp-exceptions-handling.html#webpage","url":"https://www.guru99.com/cpp-exceptions-handling.html","name":"C++ Exception Handling: Try, Catch, throw Example","dateModified":"2026-07-13T10:44:45+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/cpp-exception-handling.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/cpp-exceptions-handling.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/benjamin","name":"Benjamin Walker","description":"I'm Benjamin Walker, an expert in C, C++, and C# programming, providing resources to enhance your coding proficiency and project outcomes.","url":"https://www.guru99.com/author/benjamin","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/benjamin-walker-author.png","url":"https://www.guru99.com/images/benjamin-walker-author.png","caption":"Benjamin Walker","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"CPP","headline":"C++ Exception Handling: Try, Catch, throw Example","description":"What is Exception Handling in C++? Exception handling in C++ provides you with a way of handling unexpected circumstances like runtime errors. So whenever an unexpected circumstance occurs, the progr","keywords":"bigdata, programming, database, server","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/benjamin","name":"Benjamin Walker"},"dateModified":"2026-07-13T10:44:45+05:30","image":{"@id":"https://www.guru99.com/images/cpp-exception-handling.png"},"copyrightYear":"2026","name":"C++ Exception Handling: Try, Catch, throw Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is exception handling in C++?","acceptedAnswer":{"@type":"Answer","text":"Exception handling is a way to detect and respond to runtime errors in C++ using the try, throw, and catch keywords, so the program can recover instead of crashing."}},{"@type":"Question","name":"What are the exception handling keywords in C++?","acceptedAnswer":{"@type":"Answer","text":"C++ uses three keywords: try wraps code that might fail, throw raises an exception when an error occurs, and catch handles the thrown exception."}},{"@type":"Question","name":"What is the syntax of try-catch in C++?","acceptedAnswer":{"@type":"Answer","text":"Place risky code in a try block, then follow it with one or more catch blocks that each handle a specific exception type thrown from the try block."}},{"@type":"Question","name":"What are standard exceptions in C++?","acceptedAnswer":{"@type":"Answer","text":"Standard exceptions are built-in exception classes in the exception header, such as std::bad_alloc and std::out_of_range, that report common runtime errors."}},{"@type":"Question","name":"What is a user-defined exception in C++?","acceptedAnswer":{"@type":"Answer","text":"A user-defined exception is a custom class, often derived from std::exception, that overrides the what() function to describe your own specific error condition."}},{"@type":"Question","name":"How can AI tools like GitHub Copilot help with exception handling?","acceptedAnswer":{"@type":"Answer","text":"AI assistants like GitHub Copilot wrap risky code in try-catch blocks, generate custom exception classes, and suggest which exceptions to catch as you type."}},{"@type":"Question","name":"Can AI improve error handling in C++?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI-powered tools spot unhandled exceptions, suggest specific catch blocks over generic ones, and add meaningful error messages, making your C++ code more robust."}},{"@type":"Question","name":"What is the difference between throw and catch?","acceptedAnswer":{"@type":"Answer","text":"throw raises an exception when an error is detected, while catch receives that exception and runs the code that handles or reports the error."}}]}],"@id":"https://www.guru99.com/cpp-exceptions-handling.html#schema-1142558","isPartOf":{"@id":"https://www.guru99.com/cpp-exceptions-handling.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/cpp-exceptions-handling.html#webpage"}}]}
```
