码迷,mamicode.com
首页 > 其他好文 > 详细

try/throw/catch

时间:2014-05-01 10:21:13      阅读:407      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   tar   ext   color   art   int   rgb   type   

try 保护代码,throw抛出值,catch接受并处理异常

一般格式

mamicode.com,码迷
try
{    
//程序中抛出异常
    throw value;
}

catch(valuetype v)
{    
//异常处理程序

}
View Code

测试示例

mamicode.com,码迷
#include <iostream>

using namespace std;

int main(int argc,char *argv[])
{

    cout<< "In main"<<endl;
    //Define a try block, which is code block enclosed  by a pair of curly braces {} 
    try{
        cout<< "In the try block being ready to throw an exception"<<endl;
        //Since code being protected in the try block,so after the exception is thrown, the program  control flow will go to the next catch block.
        throw 1;
        cout<<"In the try block, because  throws an exception, so  the code here is not going to be executed"<<endl;

    }
    //Here must correspond to the definition of at least one catch block, the same it is also enclosed in curly braces
    catch(int & value)
    {
        cout<< "In the catch block,  handling the exception errors. the  exception value is  "<<value<<endl;
        cout<< "Backing into main,execution resumes here."<<endl;

    }

    cout<<"Testing finished!"<<endl;
    return 0;
}
View Code

 

 

 

 

try/throw/catch,码迷,mamicode.com

try/throw/catch

标签:style   blog   class   code   tar   ext   color   art   int   rgb   type   

原文地址:http://www.cnblogs.com/gjianw217/p/3702360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!