C++基础-(异常)

C++基础

异常

  • 程序的错误,一种是编译错误,即语法错误。另一种是运行时发生的错误
#include <iostream>
using namespace std;
int main()
{
    int n=1;
    try
    {
        int *p=new int;
        cout<<"begin"<<endl;
        if(n==1)
            throw 1;
        cout<<"after"<<endl;
    }
    catch(int)
    {
        cout<<"catch"<<endl;
        cout<<"end"<<endl;
    }
}
/*
begin
catch
end
*/
  • 异常与类的关系
#include <iostream>
using namespace std;
class test
{
    public:
        int m_z;
};
int main()
{
    int n=1;
    try
    {
        int *p=new int;
        cout<<"begin"<<endl;
        test t1;
        t1.m_z=100;
        if(n==1)
            throw t1;
        cout<<"after"<<endl;
    }
    catch(test t2)
    {
        cout<<"catch"<<t2.m_z<<endl;
    
    }
    cout<<"end"<<endl;
}
/*
begin
catch100
end
*/
  • 进化版
#include <iostream>
using namespace std;
class test
{
    public:
        int m_z;
};
class testSon::public test
{
    public:
        int m_w;
}
int main()
{
    int n=1;
    try
    {
        try
        {
            cout<<"begin"<<endl;
            test t1;
            t1.m_z=100;
            if(n==1)
                throw t1;
            cout<<"after"<<endl;
        }   
        catch(int)
        {
            cout<<"int catch"<<endl;
        }
    }
    catch(test t2)
    {
        cout<<"catch"<<t2.m_z<<endl;
    }
    catch(...)
    {
        cout<<"..."<<endl;
    }
    cout<<"end"<<endl;
}
/*
begin
catch100
end
*/
//throw 123;
/*
begin
int catch
end

*/
//throw 'a'
/*
begin
...
end
*/
//testSon t1;throw t1;
/*
begin
catch100
end
*/可以抛子类,抓父类
  • 万能捕获catch(...)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容