C++基础-(异常)

作者: I踏雪寻梅 | 来源:发表于2016-11-15 20:19 被阅读15次

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(...)

相关文章

  • C++基础-(异常)

    C++基础 异常 程序的错误,一种是编译错误,即语法错误。另一种是运行时发生的错误 异常与类的关系 进化版 万能捕...

  • (五)C++中的异常处理与模板类

    C++中的异常处理与模板类 一、C++ 中的异常处理 1、异常处理 在C++ 中可以抛出任何类型的异常,根据抛出的...

  • Android NDK开发之旅23--C++--异常处理

    异常处理 与Java类似,C++也有异常处理。 异常类型 C++中,异常的类型是任意的,如下: throw不同类型...

  • C++基础④多态,模板,异常

    接续上篇C++基础③new对象,继承,友元函数,函数的可变参数 前言 在学Java的时候 , 我们会接触到面向对象...

  • 从C到C++

    C++语言是以C语言为基础,对C语言进行了加强,如类型加强,函数加强和异常处理,最重要的是,C++加入了面向对象支...

  • 异常( Exceptions)

    异常处理是C++的一项语言机制,用于在程序中处理异常事件。异常事件在C++中表示为异常对象。 优点: 异常允许上层...

  • Android NDK来发之旅24--C++--异常处理

    Android NDK开发之旅 目录 C++ 异常处理 异常是程序在执行期间产生的问题。C++ 异常是指在程序运行...

  • Android NDK(三)- JNI 异常

    常用方法 使用例 1 - C++ 中抛出异常 使用例 2 - C++ 捕获 Java 中的异常

  • 你的c++团队还在禁用异常处理吗?

    关于c++的异常处理,网上有很多的争议,本文会介绍c++的异常处理的使用,以及我们应该使用异常处理吗,以及使用异常...

  • Go 语言基础--错误&异常浅析

    如果go是你的第一门语言,go的异常和错误体系可能比较容易接受,但如果你有一定的Java或者c++基础,go的异常...

网友评论

本文标题:C++基础-(异常)

本文链接:https://www.haomeiwen.com/subject/rsslpttx.html