---
title: "How to remove unhandled exceptions in C++?"  
description: "How to remove unhandled exceptions in C++?"  
author: "Revati S Misra"  
published: 2023-08-15  
updated: 2023-08-16  
canonical: https://www.mindstick.com/forum/159534/how-to-remove-unhandled-exceptions-in-c-plus-plus  
category: "visual c++"  
tags: ["exception handling", "exception", "c++"]  
reading_time: 2 minutes  

---

# How to remove unhandled exceptions in C++?

How to [remove](https://yourviews.mindstick.com/story/4554/8-harmful-weeds-to-remove-from-garden) [unhandled exceptions](https://www.mindstick.com/forum/159353/how-do-unhandled-exceptions-affect-jvm) in [C++](https://www.mindstick.com/blog/745/array-in-c-plus-plus)?

## Replies

### Reply by Aryan Kumar

There are two ways to remove unhandled [exceptions](https://www.mindstick.com/interview/22871/define-predifined-generic-exceptions) in C++:

- **Using** `try` **and** `catch` **blocks:** This is the most common way to handle exceptions. The `try` block contains the code that might throw an exception, and the `catch` block catches the exception and handles it.
- **Using the** `noexcept` **keyword:** The `noexcept` keyword can be used to mark a function as not throwing an exception. If an exception is thrown from a `noexcept` function, the program will terminate.

Here is an example of how to use `try` and `catch` blocks to handle exceptions:

C++

```plaintext
void foo() {
  try {
    // Code that might throw an exception
  } catch (const std::exception& e) {
    // Handle the exception
    std::cout << "Exception: " << e.what() << std::endl;
  }
}
```

Here is an example of how to use the `noexcept` keyword to prevent exceptions:

C++

```plaintext
[[noexcept]] void foo() {
  // Code that cannot throw an exception
}
```

If you are not sure whether a function can throw an exception, it is always best to use `try` and `catch` blocks to handle them. This will help to prevent your program from crashing if an exception is thrown.

Here are some additional things to keep in mind when handling exceptions in C++:

- The `catch` block must catch the specific type of exception that is thrown. If it does not, the program will terminate.
- You can use multiple `catch` blocks to catch different types of exceptions.
- The `finally` block is executed regardless of whether an exception is thrown. It is often used to clean up resources.


---

Original Source: https://www.mindstick.com/forum/159534/how-to-remove-unhandled-exceptions-in-c-plus-plus

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
