八. 异常处理和命名空间

发布时间 2023-12-04 17:23:54作者: Beasts777

1. 异常处理

注意:以下内容在C++11中进行了优化,不再适用。

C++98中,为程序可能出现的异常提供了一套完整的机制,其基本语法如下:

  • 抛出异常:

    throw 表达式;
    
  • try catch代码块:

    try{
    	复合语句
    }catch(异常类型){
        复合语句
    }catch(异常类型){
        复合语句
    }
    

抛出机制:

当函数发生异常要被抛出时,从进入try块开始,到throw异常之间在栈内构建的所有对象,都会被自动析构。析构的顺序与构造的顺序相反。这一过程被称为栈的解旋

异常接口声明:C++98为了增强程序可读性,可以在函数生命中列出那些可能抛出的异常类型,常有方式有三种:

  • 指定可以抛出的异常类型:在函数后加上throw(异常类型1, 异常类型2...)

    #include <iostream>
    #include <string>
    using namespace std;
    
    // 自己定义的异常类
    struct MyException{
        int code;
        string msg;
        MyException(int a, string s): code(a), msg(s){}
    };
    // 可以抛出MyException、int类型的异常
    double divide(int a, int b) throw (MyException, int){
        if(b == 0){
            throw MyException(1, "除数不能为0");
            // throw 1
        }
        return a/b;
    }
    
    int main(void){
        int a = 10;
        int b = 0;
        try{
            double result = divide(a, b);
        }
        catch(int e){
            cout << e << endl;
        }
        catch(MyException e){
            cout << e.code << "\t" << e.msg << endl;
        }
        return 0;
    }
    
  • 抛出任意类型的异常:在函数后不使用throw()即可。

    // 自己定义的异常类
    struct MyException{
        int code;
        string msg;
        MyException(int a, string s): code(a), msg(s){}
    };
    double divide(int a, int b){
        if(b == 0){
            throw MyException(1, "除数不能为0");
            // throw 1
        }
        return a/b;
    }
    
  • 不抛出异常:在函数后使用throw(),且不添加任何参数,表示该函数不允许抛出异常。

    // 自己定义的异常类
    struct MyException{
        int code;
        string msg;
        MyException(int a, string s): code(a), msg(s){}
    };
    double divide(int a, int b) throw()
    {
        if(b == 0){
            throw MyException(1, "除数不能为0");
            // throw 1
        }
        return a/b;
    }
    

2. 命名空间

定义:

所谓命名空间,就是一个程序设计者命名的内存区域。程序设计者可以根据需要指定一些有名字的命名空间,将各命名空间的标识符与该命名空间标识符建立关联,保证不同命名命名空间的同名标识符不发生冲突

Eg:

  • 编写命名空间文件:my_space.h

    using namespace{
        int a = 10;
        int add (int x, int y){
            return x + y;
        }
    }
    
  • 测试文件:test.cpp

    #include <iostream>
    #include "my_space.h"
    
    int main(void){
        my_space::a = 20;
        std::cout << my_space::add(1, 2) << std::endl;
        return 0;
    }
    

头文件命名规则:

  • C中:程序头文件包含扩展名.h,例如:

    #include <stdio.h>
    
  • 在C++中,程序头文件不应当包含扩展名,例如:

    #include <iostream>
    #include <cstring>