C++提供了处理异常的关键字:throw、try、catch
使用throw抛出一个异常,使用try和catch捕获异常:
- try{
- ...//保护代码
- }catch(Ex e1){
- ...//异常处理
- }catch(Ex e2){
- ...//异常处理
- }catch(Ex eN){
- ...//异常处理
- }
try块后面通常跟着1个或多个catch块,用于捕获保护代码里可能抛出的异常。当保护代码抛出异常后,程序将跳出try块(即使在另一个函数域中),并在catch块中寻找关于该异常的处理办法,Ex e中,Ex即抛出异常的类型,e即处理异常中对异常的称呼(类似函数的参数)
- #include<iostream>
- using namespace std;
-
- template<class t>
- t divide(t a,t b){
- if(b==0) throw"Devided by zero!";
- return a/b;
- }
-
- int main(){
- try{
- cout<<divide(10,5)<<endl<<divide(10,0)<<endl<<divide(18,2)<<endl;
- }
- catch(const char* err){
- cerr<<err<<endl; //std::cerr标准错误流异常输出
- }
- return 0;
- }
编译 & 运行:
- g++ -o executable main1.c
-
- ./executable
结果:
不难看出,当try块中抛出异常后,程序将第一时间退出保护代码,后面的语句不会被执行。