C++異常捕獲是在運行時進行的,但是拋出的對象卻是在編譯時確定的,編譯時會對拋出的對象上溯查找到無二義性的基類,然后拋出這個對象的引用。
例如:
#include <iostream>
using namespace std;
class CBase
{
public:
virtual ~CBase(){};
};
class CDerived:public CBase
{
};
void exceMaker()
{
throw CDerived();
}
void exceCatcher()
{
try
{
exceMaker();
}
catch(CBase&)
{
cout << "caught a CBase" << endl;
}
catch(...)
{
cout << "caught else" << endl;
}
}
int main(int argc, char** argv)
{
exceCatcher();
cin.get();
return 0;
}
運行后將打印出:
caught a CBase.
編譯器進行了類型上溯轉換,拋出的CBase的引用,如果同時捕獲CDerived&,也即在exce中加入如下代碼:
catch(CDerived&)
{
cout << "caught a CDerived" << endl;
}
編譯時將會給出warning,說異常已經被 catch(CBase&)捕獲,證明在編譯時進行了轉換。
而如果修改CDerived 為私有繼承CBase,整體代碼如下:
#include <iostream>
using namespace std;
class CBase
{
public:
virtual ~CBase(){};
};
class CDerived:private CBase
{
};
void exceMaker()
{
throw CDerived();
}
void exceCatcher()
{
try
{
exceMaker();
}
catch(CBase&)
{
cout << "caught a CBase" << endl;
}
catch(...)
{
cout << "caught else" << endl;
}
}
int main(int argc, char** argv)
{
exceCatcher();
cin.get();
return 0;
}
將打印出"caught else";
因為私有繼承后,exceMaker函數不能對私有繼承的基類進行上溯(private權限限制),所以拋出的異常為CDerived&,不再是CBase&.
而如果這樣:
#include <iostream>
using namespace std;
class CBase
{
public:
virtual ~CBase(){};
};
class CDerived:private CBase
{
friend void exceMaker();
};
void exceMaker()
{
throw CDerived();
}
void exceCatcher()
{
try
{
exceMaker();
}
catch(CBase&)
{
cout << "caught a CBase" << endl;
}
catch(...)
{
cout << "caught else" << endl;
}
}
int main(int argc, char** argv)
{
exceCatcher();
cin.get();
return 0;
}
在VC6中將打印出"caught CBase",因為exceMaker是CDerived的友元函數,可以訪問它的私有成員,故可以上溯到CBase&,但后續的編譯器版本已經更正為caught else. 因為不是ISA關系。