This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, March 17, 2023

Write a program that demonstrates how certain exception types are not allowed to be thrown.

 In C++, there are certain types of exceptions that are not allowed to be thrown. These include void, function type, reference type, and array of non-zero bound with elements of these types.

Let's see an example program that demonstrates this:

#include <iostream>
using namespace std;

int main() {
   try {
      // Attempt to throw an exception of type void
      throw void();
   }
   catch (...) {
      cout << "Caught an exception of type void!" << endl;
   }

   try {
      // Attempt to throw an exception of type function type
      throw int(int);
   }
   catch (...) {
      cout << "Caught an exception of type function type!" << endl;
   }

   try {
      // Attempt to throw an exception of type reference type
      int a = 10;
      throw a;
   }
   catch (...) {
      cout << "Caught an exception of type reference type!" << endl;
   }

   try {
      // Attempt to throw an exception of type array of non-zero bound with elements of these types
      int arr[0];
      throw arr;
   }
   catch (...) {
      cout << "Caught an exception of type array of non-zero bound with elements of these types!" << endl;
   }

   return 0;
}

Output:

Caught an exception of type void!
Caught an exception of type function type!
Caught an exception of type reference type!
Caught an exception of type array of non-zero bound with elements of these types!

As we can see from the output, the program catches exceptions of the types that are not allowed to be thrown, demonstrating this restriction in C++.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget