Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character thrown but integer catched: how are promotions and conversions handled with exceptions?

Tags:

c++

try-catch

I'm programming some exercises about exceptions in C++ with NetBeans 8.1 Patch 1 on Windows 10 using MinGW 64 bits, but the expected result is not the same when I execute the code in IDE.

Here's the code:

#include <cstdlib>
#include <iostream>

using namespace std;

void f() { 
   throw 'A';
}

int main() {
   try { 
      try { 
         f();
      } catch (int) { 
         cout << "In catch (int) 1" << endl;
         throw;
      } catch (...) {
         cout << "In catch (...) 1" << endl;
         throw 65;
      }
   } catch (int&) {
           cout << "In catch (int&)" << endl;
   } catch (int) {
           cout << "In catch (int) 2" << endl;
   } catch (const int) {
           cout << "In catch (const int)" << endl;
   } catch (...) {
           cout << "In catch (...) 2" << endl;
   }

   cout << "End of program" << endl;
   return EXIT_SUCCESS;
}

The terminal displays this :

In catch (int) 1
In catch (int&)
End of program

Normally, the terminal should display in the first line "In catch(...) 1", but I don't understand why the IDE doesn't display the good result.

I tried this code with g++ on PowerShell, same result, but with g++ on Linux Ubuntu, he displays the right result.

I don't have any suggestions.

Thank you for your help. Kind regards.

like image 804
ZeRedDiamond Avatar asked Jan 01 '26 00:01

ZeRedDiamond


1 Answers

Integral promotions are considered when a suitable catch is searched for. 'A' is a character literal and is promoted to an int.

Thus:

  1. throw 'A'; is performed;
  2. catch (int) after integral promotion;
  3. throw; rethrows the same object (no copy is made);
  4. catch (int&) catches it (note: catch (int) could catch it but it is not the nearest catch);
  5. program ends.

For your information, [except.throw]/2 explains what nearest means:

When an exception is thrown, control is transferred to the nearest handler with a matching type ([except.handle]); “nearest” means the handler for which the compound-statement or ctor-initializer following the try keyword was most recently entered by the thread of control and not yet exited.

like image 168
YSC Avatar answered Jan 03 '26 15:01

YSC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!