C++解析(28):异常处理

摘要:
示例——异常处理代码分析:#includeusingnamespacestd;#defineSUCCESS0#defineINVALID_POINTER-1#defineINVALID_LENGTH-2#defineINVALID_PARAMETER-3intMemSet{if{returnINVALID_POINTER;}if{returnINVALID_LENGTH;}if{returnINVALID_PARAMETER;}unsignedchar*p=dest;for{p[i]=v;}returnSUCCESS;}intmain{intai[5];intret=MemSet;if{}elseif{}elseif{}elseif{}returnret;}2.C++中的异常处理C++内置了异常处理的语法元素try...catch...:try语句处理正常代码逻辑catch语句处理异常情况try语句中的异常由对应的catch语句处理C++通过throw语句抛出异常信息:throw抛出的异常必须被catch处理:当前函数能够处理异常,程序继续往下执行当前函数无法处理异常,则函数停止执行,并返回未被处理的异常会顺着函数调用栈向上传播,直到被处理为止,否则程序将停止执行。示例——C++异常处理:#includeusingnamespacestd;doubledivide{constdoubledelta=0.000000000000001;doubleret=0;if(!

0.目录

1.C语言异常处理

2.C++中的异常处理

3.小结

1.C语言异常处理

异常的概念:

  • 程序在运行过程中可能产生异常
  • 异常Exception)与 Bug 的区别
    1. 异常是程序运行时可预料的执行分支
    2. Bug 是程序的错误,是不被预期的运行方式

异常(Exception)与 Bug 的对比:

  • 异常
    1. 运行时产生除0的情况
    2. 需要打开的外部文件不存在
    3. 数组访问时越界
  • Bug
    1. 使用野指针
    2. 堆数组使用结束后未释放
    3. 选择排序无法处理长度为0的数组

异常处理的方式:
C语言经典处理方式:if ... else ...
C++解析(28):异常处理第1张

示例——除法操作异常处理:

#include <iostream>

using namespace std;

double divide(double a, double b, int* valid)
{
    const double delta = 0.000000000000001;
    double ret = 0;
    
    if( !((-delta < b) && (b < delta)) )
    {
        ret = a / b;
        
        *valid = 1;
    }
    else
    {
        *valid = 0;
    }
    
    return ret;
}

int main(int argc, char *argv[])
{   
    int valid = 0;
    double r = divide(1, 0, &valid);
    
    if( valid )
    {
        cout << "r = " << r << endl;
    }
    else
    {
        cout << "Divided by zero..." << endl;
    }
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
Divided by zero...

缺陷:

  • divide函数有3个参数,难以理解其用法
  • divide函数调用后必须判断valid代表的结果
    1. 当valid为true时,运算结果正常
    2. 当valid为false时,运算结果出现异常

通过 setjmp()longjmp() 进行优化:

  • int setjmp(jmp_buf env)
    1. 将当前上下文保存在jmp_buf结构体中
  • void longjmp(jmp_buf env, int val)
    1. 从jmp_buf结构体中恢复setjmp()保存的上下文
    2. 最终从setjmp函数调用点返回,返回值为val

示例——除法操作异常处理优化:

#include <iostream>
#include <csetjmp>

using namespace std;

static jmp_buf env;

double divide(double a, double b)
{
    const double delta = 0.000000000000001;
    double ret = 0;
    
    if( !((-delta < b) && (b < delta)) )
    {
        ret = a / b;
    }
    else
    {
        longjmp(env, 1);
    }
    
    return ret;
}

int main(int argc, char *argv[])
{   
    if( setjmp(env) == 0 )
    {
        double r = divide(1, 0);
        
        cout << "r = " << r << endl;
    }
    else
    {
        cout << "Divided by zero..." << endl;
    }
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
Divided by zero...

setjmp() 和 longjmp() 的引入:

  • 必然涉及到使用全局变量
  • 暴力跳转导致代码可读性降低
  • 本质还是if ... else ... 异常处理方式

C语言中的经典异常处理方式会使得程序中逻辑中混入大量的处理异常的代码。
正常逻辑代码和异常处理代码混合在一起,导致代码迅速膨胀,难以维护。。。

示例——异常处理代码分析:

#include <iostream>

using namespace std;

#define SUCCESS           0 
#define INVALID_POINTER   -1
#define INVALID_LENGTH    -2
#define INVALID_PARAMETER -3

int MemSet(void* dest, unsigned int length, unsigned char v)
{
    if( dest == NULL )
    {
        return INVALID_POINTER;
    }
    
    if( length < 4 )
    {
        return INVALID_LENGTH;
    }
    
    if( (v < 0) || (v > 9) )
    {
        return INVALID_PARAMETER;
    }
    
    unsigned char* p = (unsigned char*)dest;
    
    for(int i=0; i<length; i++)
    {
        p[i] = v;
    }
    
    return SUCCESS;
}

int main(int argc, char *argv[])
{
    int ai[5];
    int ret = MemSet(ai, sizeof(ai), 0);
    
    if( ret == SUCCESS )
    {
    }
    else if( ret == INVALID_POINTER )
    {
    }
    else if( ret == INVALID_LENGTH )
    {
    }
    else if( ret == INVALID_PARAMETER )
    {
    }
    
    return ret;
}

2.C++中的异常处理

C++内置了异常处理的语法元素try ... catch ...

  • try语句处理正常代码逻辑
  • catch语句处理异常情况
  • try语句中的异常由对应的catch语句处理

C++解析(28):异常处理第2张

C++通过throw语句抛出异常信息:
C++解析(28):异常处理第3张

throw抛出的异常必须被catch处理:

  • 当前函数能够处理异常,程序继续往下执行
  • 当前函数无法处理异常,则函数停止执行,并返回

未被处理的异常会顺着函数调用栈向上传播,直到被处理为止,否则程序将停止执行。
C++解析(28):异常处理第4张

示例——C++异常处理:

#include <iostream>

using namespace std;

double divide(double a, double b)
{
    const double delta = 0.000000000000001;
    double ret = 0;
    
    if( !((-delta < b) && (b < delta)) )
    {
        ret = a / b;
    }
    else
    {
        throw 0;
    }
    
    return ret;
}

int main(int argc, char *argv[])
{    
    try
    {
        double r = divide(1, 0);
            
        cout << "r = " << r << endl;
    }
    catch(...)
    {
        cout << "Divided by zero..." << endl;
    }
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
Divided by zero...

同一个try语句可以跟上多个catch语句:

  • catch语句可以定义具体处理的异常类型
  • 不同类型的异常由不同的catch语句负责处理
  • try语句中可以抛出任何类型的异常
  • catch(...)用于处理所有类型的异常
  • 任何异常都只能被捕获(catch)一次

异常处理的匹配规则:
C++解析(28):异常处理第5张

示例——异常类型匹配:

#include <iostream>

using namespace std;

void Demo1()
{
    try
    {   
        throw 'c';
    }
    catch(char c)
    {
        cout << "catch(char c)" << endl;
    }
    catch(short c)
    {
        cout << "catch(short c)" << endl;
    }
    catch(double c)
    {
        cout << "catch(double c)" << endl;
    }
    catch(...)
    {
        cout << "catch(...)" << endl;
    }
}

void Demo2()
{
    throw string("HelloWorld!");
}

int main(int argc, char *argv[])
{    
    Demo1();
    
    try
    {
        Demo2();
    }
    catch(char* s)
    {
        cout << "catch(char *s)" << endl;
    }
    catch(const char* cs)
    {
        cout << "catch(const char *cs)" << endl;
    }
    catch(string ss)
    {
        cout << "catch(string ss)" << endl;
    }
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
catch(char c)
catch(string ss)

catch语句块中可以抛出异常:
C++解析(28):异常处理第6张

为什么要在catch中重新抛出异常?

  • catch中捕获的异常可以被重新解释后抛出
  • 工程开发中使用这样的方式统一异常类型

C++解析(28):异常处理第7张

示例——在catch中重新抛出异常:

#include <iostream>

using namespace std;

void Demo()
{
    try
    {
        try
        {
            throw 'c';
        }
        catch(int i)
        {
            cout << "Inner: catch(int i)" << endl;
            throw i;
        }
        catch(...)
        {
            cout << "Inner: catch(...)" << endl;
            throw;
        }
    }
    catch(...)
    {
        cout << "Outer: catch(...)" << endl;
    }
}

int main(int argc, char *argv[])
{
    Demo();
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
Inner: catch(...)
Outer: catch(...)

示例——异常的重新解释:

#include <iostream>

using namespace std;

/*
    假设: 当前的函数式第三方库中的函数,因此,我们无法修改源代码
    
    函数名: void func(int i)
    抛出异常的类型: int
                        -1 ==》 参数异常
                        -2 ==》 运行异常
                        -3 ==》 超时异常
*/
void func(int i)
{
    if( i < 0 )
    {
        throw -1;
    }
    
    if( i > 100 )
    {
        throw -2;
    }
    
    if( i == 11 )
    {
        throw -3;
    }
    
    cout << "Run func..." << endl;
}

void MyFunc(int i)
{
    try
    {
        func(i);
    }
    catch(int i)
    {
        switch(i)
        {
            case -1:
                throw "Invalid Parameter";
                break;
            case -2:
                throw "Runtime Exception";
                break;
            case -3:
                throw "Timeout Exception";
                break;
        }
    }
}

int main(int argc, char *argv[])
{
    try
    {
        MyFunc(11);
    }
    catch(const char* cs)
    {
        cout << "Exception Info: " << cs << endl;
    }
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
Exception Info: Timeout Exception

C++中的异常处理:

  • 异常的类型可以是自定义类类型
  • 对于类类型异常的匹配依旧是至上而下严格匹配
  • 赋值兼容性原则在异常匹配中依然适用
  • 一般而言
    1. 匹配子类异常的catch放在上部
    2. 匹配父类异常的catch放在下部

(根据赋值兼容性原则:子类的异常对象可以被父类的catch语句块抓住。)

C++中的异常处理:

  • 在工程中会定义一系列的异常类
  • 每个类代表工程中可能出现的一种异常类型
  • 代码复用时可能需要重解释不同的异常类
  • 在定义catch语句块时推荐使用引用作为参数

示例——类类型的异常:

#include <iostream>

using namespace std;

class Base
{
};

class Exception : public Base
{
    int m_id;
    string m_desc;
public:
    Exception(int id, string desc)
    {
        m_id = id;
        m_desc = desc;
    }
    
    int id() const
    {
        return m_id;
    }
    
    string description() const
    {
        return m_desc;
    }
};

/*
    假设: 当前的函数式第三方库中的函数,因此,我们无法修改源代码
    
    函数名: void func(int i)
    抛出异常的类型: int
                        -1 ==》 参数异常
                        -2 ==》 运行异常
                        -3 ==》 超时异常
*/
void func(int i)
{
    if( i < 0 )
    {
        throw -1;
    }
    
    if( i > 100 )
    {
        throw -2;
    }
    
    if( i == 11 )
    {
        throw -3;
    }
    
    cout << "Run func..." << endl;
}

void MyFunc(int i)
{
    try
    {
        func(i);
    }
    catch(int i)
    {
        switch(i)
        {
            case -1:
                throw Exception(-1, "Invalid Parameter");
                break;
            case -2:
                throw Exception(-2, "Runtime Exception");
                break;
            case -3:
                throw Exception(-3, "Timeout Exception");
                break;
        }
    }
}

int main(int argc, char *argv[])
{
    try
    {
        MyFunc(11);
    }
    catch(const Exception& e)
    {
        cout << "Exception Info: " << endl;
        cout << "   ID: " << e.id() << endl;
        cout << "   Description: " << e.description() << endl;
    }
    catch(const Base& e)
    {
        cout << "catch(const Base& e)" << endl;
    }
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
Exception Info: 
   ID: -3
   Description: Timeout Exception

C++中的异常处理:

  • C++标准库中提供了实用异常类族
  • 标准库中的异常都是从exception类派生的
  • exception类有两个主要的分支
    1. logic_error——常用于程序中的可避免逻辑错误
    2. runtime_error——常用于程序中无法避免的恶性错误

标准库中的异常:
C++解析(28):异常处理第8张

示例——标准库中的异常使用(优化之前的Array.h和HeapArray.h):

// Array.h
#ifndef _ARRAY_H_
#define _ARRAY_H_

#include <stdexcept>

using namespace std;

template
< typename T, int N >
class Array
{
    T m_array[N];
public:
    int length() const;
    bool set(int index, T value);
    bool get(int index, T& value);
    T& operator[] (int index);
    T operator[] (int index) const;
    virtual ~Array();
};

template
< typename T, int N >
int Array<T, N>::length() const
{
    return N;
}

template
< typename T, int N >
bool Array<T, N>::set(int index, T value)
{
    bool ret = (0 <= index) && (index < N);
    
    if( ret )
    {
        m_array[index] = value;
    }
    
    return ret;
}

template
< typename T, int N >
bool Array<T, N>::get(int index, T& value)
{
    bool ret = (0 <= index) && (index < N);
    
    if( ret )
    {
        value = m_array[index];
    }
    
    return ret;
}

template
< typename T, int N >
T& Array<T, N>::operator[] (int index)
{
    if( (0 <= index) && (index < N) )
    {
        return m_array[index];
    }
    else
    {
        throw out_of_range("T& Array<T, N>::operator[] (int index)");
    }
}

template
< typename T, int N >
T Array<T, N>::operator[] (int index) const
{
    if( (0 <= index) && (index < N) )
    {
        return m_array[index];
    }
    else
    {
        throw out_of_range("T Array<T, N>::operator[] (int index) const");
    }
}

template
< typename T, int N >
Array<T, N>::~Array()
{
}

#endif
// HeapArray.h
#ifndef _HEAPARRAY_H_
#define _HEAPARRAY_H_

#include <stdexcept>

using namespace std;

template
< typename T >
class HeapArray
{
private:
    int m_length;
    T* m_pointer;
    
    HeapArray(int len);
    HeapArray(const HeapArray<T>& obj);
    bool construct();
public:
    static HeapArray<T>* NewInstance(int length); 
    int length() const;
    bool get(int index, T& value);
    bool set(int index ,T value);
    T& operator [] (int index);
    T operator [] (int index) const;
    HeapArray<T>& self();
    const HeapArray<T>& self() const;
    ~HeapArray();
};

template
< typename T >
HeapArray<T>::HeapArray(int len)
{
    m_length = len;
}

template
< typename T >
bool HeapArray<T>::construct()
{   
    m_pointer = new T[m_length];
    
    return m_pointer != NULL;
}

template
< typename T >
HeapArray<T>* HeapArray<T>::NewInstance(int length) 
{
    HeapArray<T>* ret = new HeapArray<T>(length);
    
    if( !(ret && ret->construct()) ) 
    {
        delete ret;
        ret = 0;
    }
        
    return ret;
}

template
< typename T >
int HeapArray<T>::length() const
{
    return m_length;
}

template
< typename T >
bool HeapArray<T>::get(int index, T& value)
{
    bool ret = (0 <= index) && (index < length());
    
    if( ret )
    {
        value = m_pointer[index];
    }
    
    return ret;
}

template
< typename T >
bool HeapArray<T>::set(int index, T value)
{
    bool ret = (0 <= index) && (index < length());
    
    if( ret )
    {
        m_pointer[index] = value;
    }
    
    return ret;
}

template
< typename T >
T& HeapArray<T>::operator [] (int index)
{
    if( (0 <= index) && (index < length()) )
    {
        return m_pointer[index];
    }
    else
    {
        throw out_of_range("T& HeapArray<T>::operator [] (int index)");
    }
}

template
< typename T >
T HeapArray<T>::operator [] (int index) const
{
    if( (0 <= index) && (index < length()) )
    {
        return m_pointer[index];
    }
    else
    {
        throw out_of_range("T HeapArray<T>::operator [] (int index) const");
    }
}

template
< typename T >
HeapArray<T>& HeapArray<T>::self()
{
    return *this;
}

template
< typename T >
const HeapArray<T>& HeapArray<T>::self() const
{
    return *this;
}

template
< typename T >
HeapArray<T>::~HeapArray()
{
    delete[]m_pointer;
}

#endif
// test.cpp
#include <iostream>
#include "Array.h"
#include "HeapArray.h"

using namespace std;

void TestArray()
{
    Array<int, 5> a;
    
    for(int i=0; i<a.length(); i++)
    {
        a[i] = i;
    }
        
    for(int i=0; i<a.length(); i++)
    {
        cout << a[i] << endl;
    }
}

void TestHeapArray()
{
    HeapArray<double>* pa = HeapArray<double>::NewInstance(5);
    
    if( pa != NULL )
    {
        HeapArray<double>& array = pa->self();
        
        for(int i=0; i<array.length(); i++)
        {
            array[i] = i;
        }
            
        for(int i=0; i<array.length(); i++)
        {
            cout << array[i] << endl;
        }
    }
    
    delete pa;
}

int main(int argc, char *argv[])
{
    try
    {
        TestArray();
        
        cout << endl;
        
        TestHeapArray();
    }
    catch(...)
    {
        cout << "Exception" << endl;
    }
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
0
1
2
3
4

0
1
2
3
4

3.小结

  • 程序中不可避免的会发生异常
  • 异常是在开发阶段就可以预见的运行时问题
  • C语言中通过经典的if .... else ... 方式处理异常
  • C++中存在更好的异常处理方式
  • C++中直接支持异常处理的概念
  • try ... catch ... 是C++中异常处理的专用语句
  • try语句处理正常代码逻辑,catch语句处理异常情况
  • 同一个try语句可以跟上多个catch语句
  • 异常处理必须严格匹配,不进行任何的类型转换
  • catch语句块中可以抛出异常
  • 异常的类型可以是自定义类类型
  • 赋值兼容性原则在异常匹配中依然适用
  • 标准库中的异常都是从exception类派生的

免责声明:文章转载自《C++解析(28):异常处理》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇NetBus —— 让你的 App 内部随处感知网络的变化26个高效工作的小技巧(转载)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

多线程中如何取消任务

大多数情况下,任务运行完后会自动结束。然而,有时我们希望提前结束任务或线程,可能是因为用户取消了操作,或者应用程序需要被快速关闭。但是,Java并没有提供任务机制来安全地终止线程。虽然如此,但Java提供了线程中断,中断是一种协作机制,能使一个线程终止另一个线程的当前工作。 我们很少希望某个任务、线程或服务立即停止,因为这种立即停止会使共享数据处于不一致的...

类3(友元)

一、友元介绍 我们知道,类的成员函数可以访问同类的其他成员函数,包括公有、私有和保护成员。而类的外部函数只能访问类的公有成员。友元是一种允许非类成员函数访问类的非公有成员的一种机制。可以把一个函数指定为类的友元,也可以把整个类指定为另一个类的友元。 友元函数友元类 二、友元函数友元函数在类作用域外定义,但它需要在类体中进行说明为了与该类的成员函数加以区别,...

zookeeper(五) curator 锁机制

分布式锁的应用 分布式锁服务宕机, ZooKeeper 一般是以集群部署, 如果出现 ZooKeeper 宕机, 那么只要当前正常的服务器超过集群的半数, 依然可以正常提供服务持有锁资源服务器宕机, 假如一台服务器获取锁之后就宕机了, 那么就会导致其他服务器无法再获取该锁. 就会造成 死锁 问题, 在 Curator 中, 锁的信息都是保存在临时节点上,...

[Errno 256] No more mirrors to try.错误的解决方式

q 在centOS 7系统上搭建Mysql服务器时,报以下错误: Error downloading packages: vsftpd-3.0.2-22.el7.x86_64: [Errno 256] No more mirrors to try. [root@localhost ~]# 解决方式: 1、yum clean all 2、...

弱回调与std::forward

  weak callback template<typename CLASS, typename... ARGS> class WeakCallback { public: WeakCallback(const std::weak_ptr<CLASS>& object, const s...

微信小程序-上传多张图片加进度,持续修正中……

tips.参考网上资料的改进版 1.怎么使用.html <!--无限制需要在js代码里设置数量,upload为上传地址,或者说图片服务器 --> <up-pic url="{{upload}}"bindupImgData="upImgData"class='up-pic' notli/>...