Why does catching a const int & by an int& work?

  • A+

In the following code, I throw an int, catch it as const int&, re-throw it and catch it again catch it as an int&.

#include <iostream>  int main() {     try     {         try         {             int x = 1;             throw x;         }         catch(const int& e)         {             std::cout << "Inner catch" << std::endl;             throw e;         }     }     catch(int & e1)     {         std::cout << "Outer catch" << std::endl;     }      return 0; } 

The above program compiles successfully and prints

Inner catch Outer catch 

On the other hand the following program in which I am trying to initialize an int& by a const int& wouldn't even compile.

#include <iostream> int main() {     int x = 0;     const int& y = x;     int& z = y      return 0; } 

I get the following error as expected

binding ‘const int’ to reference of type ‘int&’ discards qualifiers      int& z = y 

Why am I allowed to catch an const int& as an int& but not able to assign cons int& to int&?



A handler is a match for an exception object of type E if
(3.1) – The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or [...]


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: