栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

(C++)异常处理

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

(C++)异常处理

1、异常的概念

异常处理就是处理程序中的错误,错误就是程序在运行期间发生的一些异常事件,(栈溢出,转换失败,数组下标越界等)。

2、异常的语法

throw:抛出异常 , 代替return语句

try         //检查可能发生异常的语句

{

...........

}

catch      //铺获异常

{
...........
}

3、异常处理实例

除0自然会产生异常

#include 
using namespace std;

int Div(int x,int y)
{
    if(0 == y)
    {
        throw 0;         //抛出异常
    }
    return x / y;
}
int main(int argc, char const *argv[])
{
    int a,b;
    cin >>a>>b;
    try             //把可能发生异常的语句放在try语句中
    {
        cout<
4、异常的思想
#include 
using namespace std;
int Div(int x,int y)
{
    return DDiv(x,y);
}
int DDiv(int x,int y)
{
    if(0 == y)
    {
        //throw 0;            //抛出异常
        throw 'a';            //抛出异常
    }
    return x / y;
}
int main(int argc, char const *argv[])
{
    int a,b;
    cin>>a>>b;
    try
    {
        cout<
5、异常的声明
#include 
using namespace std;
//int Div(int x,int y);   //可能抛出任何异常
//int Div(int x,int y) throw(int,char);    //只能输出int,char类型的异常
int Div(int x,int y) throw();   //不会输出任何异常
int main(int argc, char const *argv[])
{
    int a,b;
    cin>>a>>b;
    try
    {
        cout<
6、异常对象
#include 
using namespace std;
class Test
{
    public:
        Test()
        {
            cout<<"Test的构造函数"<>a>>b;
    try
    {
        cout 
7、标准异常库 

c++提供了一组标准异常类,这些类以基类exception开始,标准程序库中抛出的所有异常都派生于该基类

virtual const char *what() const throw() = 0;

//exception 提供的一个虚函数 what() 用来返回错误信息

exception--->bad_alloc, bad_cast, bad_typeid, over_flow, logic_error

//bad_alloc : new 或者 new[ ] 分配内存失败抛出异常

//bad_cast : dynamic_cast 转换失败抛出异常

//bad_typeid : typeid 操作空指针,而且该指针带有虚函数的类,抛出异常

//over_fiow: 计算错误(上溢),抛出异常

//logic_error :逻辑错误,有派生类 out_of_range 超出有效范围  

#include 
#include 
using namespace std;
int func(int *a,int index)
{
    if(index > 2)
    {
        throw out_of_range("index不能小于2");
    }
}
int main(int argc, char const *argv[])
{
    int a[3] = {1,2,3};
    try
    {
        func(a,10);
    }
    catch(const std::exception& e)
    {
       cout< 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/934460.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号