• Home
  • Languages
    • C++
  • Mobile
    • Android
  • Desktop
    • WinForms
  • Install Our Apps
C++ Snippets

Type and hit Enter to search

  • Home
  • Languages
    • C++
  • Mobile
    • Android
  • Desktop
    • WinForms
  • Install Our Apps
Language Constructs

C++ Exception Handling

Admin
December 15, 2021 One Min Read
3 Views
0 Comments

Learn Exception handling in C++ via simple code snippets.

Snippet 1: Argument Exception

How to handle argument exception in C++

#include <exception>
#include <iostream>
#include <string>

using namespace std;

auto divide_by_two(int num) {
  // If num is an odd number, throw an ArgumentException.
  if ((num & 1) == 1)
    throw invalid_argument("Number must be even");

  // num is even, return half of its value.
  return num / 2;
}

// The main entry point for the application.
int main() {
  // ArgumentException is not thrown because 10 is an even number.
  cout << "10 divided by 2 is " << divide_by_two(10) << endl;
  try {
    // ArgumentException is thrown because 7 is not an even number.
    cout << "7 divided by 2 is " << divide_by_two(7) << endl;
  } catch (const invalid_argument&) {
    // Show the user that 7 cannot be divided by 2.
    cout << "7 is not divided by 2 integrally." << endl;
  }
}

This code produces the following output:

10 divided by 2 is 5
7 is not divided by 2 integrally.

Snippet 2: Exception Pointer

C++ Exception Pointer Example:

#include <cstdint>
#include <exception>
#include <iostream>
#include <thread>

using namespace std;

auto main() -> int {
  exception_ptr exceptionPointer;

  thread thread([&] {
    try {
      throw logic_error("Ouch there are an exception !");
    } catch (...) {
      exceptionPointer = current_exception();
    }
  });

  thread.join();

  if (exceptionPointer) {
    try {
      rethrow_exception(exceptionPointer);
    } catch (const logic_error& exception) {
      cout << exception.what() << endl;
    }
  }
}

This code produces the following output:

Ouch there are an exception !

Share Article

Follow Me Written By

Admin

Other Articles

Previous

C++ Console Snippets

Next

C++ DateTime Snippets

Next
December 15, 2021

C++ DateTime Snippets

Previews
December 15, 2021

C++ Console Snippets

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

All Right Reserved!