c++ 异常处理

本文介绍 C++ 中异常处理的基本概念,包括 throw、try 和 catch 的使用,并通过示例展示如何结合多态特性增强异常处理能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      c++ 异常处理设计到三个关键字,分别是throw,try和catch。

      程序使用throw抛出异常,将可能出错的程序段放在try中,并用catch进行捕获。

      先举个例子:

<pre name="code" class="cpp">#include <iostream>
#include <string>
using namespace std;
void test()
{
    throw "exception";
    cout<<"test()"<<endl;
}

int main()
{
    try{
        test();
    }
    catch(const char *str)
    {
        cout<<str<<endl;
    }
}


      程序将输出:

       exception

      如上程序,将可能抛出异常的test程序放入try语句块中,然后执行到test中,抛出异常,使用catch捕获,将异常输出。注意当test中异常发生后,test程序段后面的程序部分将不会输出,也就是程序中的test()语句。

      当然,一般我们在程序中可能会多加几个catch,使得捕获的异常的类型更多。

      一般关于普通的异常就是这样,但是我们写程序有可能会将异常和c++多态结合起来,这样异常就显得高大上了。

      

<pre name="code" class="cpp">#include <iostream>
using namespace std;

class Exception{
public:
    virtual void printException()
	{
        cout<<"Exception printException()"<<endl;
	}
    virtual ~Exception(){}
};

class IndexException : public Exception
{
    virtual void printException()
	{
        cout<<"Index Exception printException()"<<endl;
	}
    virtual ~IndexException(){}
};

void test()
{
    throw IndexException();
}

int main()
{
    try{
        test();
	}
	catch(const Exception &e)
	{
        e.printException();
	}
}


      输出:

      

   Index Exception printException()

      这样我们可以定义一个接口类,作为一个异常处理的基类,然后在用各种继承类继承接口类,在异常处理捕获的时候只需用基类的类,这样依据多态特性,程序自然能正确处理传入异常的实际的参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值