首页 > 代码库 > try/throw/catch

try/throw/catch

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

一般格式

try
{    
//程序中抛出异常
    throw value;
}

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

}
View Code

测试示例

#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