C++ | C++异常处理

2021/9/13 22:07:53

本文主要是介绍C++ | C++异常处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

C++ | C++异常处理

C++ 异常处理

异常是程序在执行期间产生的问题。C++ 异常是指在程序运行时发生的特殊情况,比如尝试除以零的操作。

异常提供了一种转移程序控制权的方式。C++ 异常处理涉及到三个关键字:try、catch、throw

  • throw: 当问题出现时,程序会抛出一个异常。这是通过使用 throw 关键字来完成的。
  • catch: 在您想要处理问题的地方,通过异常处理程序捕获异常。catch 关键字用于捕获异常。
  • try: try 块中的代码标识将被激活的特定异常。它后面通常跟着一个或多个 catch 块。

如果有一个块抛出一个异常,捕获异常的方法会使用 trycatch 关键字。
try 块中放置可能抛出异常的代码,try 块中的代码被称为保护代码。使用 try/catch 语句的语法如下所示:

try
{
   // 保护代码
}catch( ExceptionName e1 )
{
   // catch 块
}catch( ExceptionName e2 )
{
   // catch 块
}catch( ExceptionName eN )
{
   // catch 块
}

如果 try 块在不同的情境下会抛出不同的异常,这个时候可以尝试罗列多个 catch 语句,用于捕获不同类型的异常

抛出异常

您可以使用 throw 语句在代码块中的任何地方抛出异常
throw 语句的操作数可以是任意的表达式,表达式的结果的类型决定了抛出的异常的类型

实例1:

/*******************************************************************
 *   > File Name: throw.cpp
 *   > Create Time: 2021年09月13日  9:08:11
 ******************************************************************/
#include <iostream>
using namespace std;

double division(int a, int b)
{
    if (b == 0) /* 尝试除以零时抛出异常 */
    {
        throw "Division by zero condition!";
        return (-1);
    }

    return (a/b);
}

int main(void)
{
    division(8, 0);
    return 0;
}

编译、运行:

PS E:\fly-prj\cplusplus\day11> make 
g++ -o throw throw.cpp -g -Wall
PS E:\fly-prj\cplusplus\day11> .\throw.exe
terminate called after throwing an instance of 'char const*'
      0 [main] throw 1869 cygwin_exception::open_stackdumpfile: Dumping stack trace to throw.exe.stackdump

捕获异常

catch 块跟在 try 块后面,用于捕获异常。
您可以指定想要捕捉的异常类型,这是由 catch 关键字后的括号内的异常声明决定的。

try
{
   // 保护代码
}catch( ExceptionName e )
{
  // 处理 ExceptionName 异常的代码
}

上面的代码会捕获一个类型为 ExceptionName 的异常。
如果想让 catch 块能够处理 try 块抛出的任何类型的异常,则必须在异常声明的括号内使用省略号 …,如下所示:

try
{
   // 保护代码
}catch(...)
{
  // 能处理任何异常的代码
}

实例2:

/*******************************************************************
 *   > File Name: try-catch.cpp
 *   > Create Time: 2021年09月13日  9:24:33
 ******************************************************************/
#include <iostream>
using namespace std;

double division(int a, int b)
{
    if (b == 0)
    {
        throw "Division by zero condition!";
        return (-1);
    }

    return (a/b);
}

int main(void)
{
    int x = 50;
    int y = 0;
    double d = 0.0;

    try
    {
        d = division(x, y);
        cout << "d = " << d << endl;
    }
    catch(const char *msg)
    {
        cerr << msg << endl;
    }

    return 0;
}

编译、运行:

## 抛出了一个类型为 const char* 的异常,因此,当捕获该异常时,必须在 catch 块中使用 const char*。
PS E:\fly-prj\cplusplus\day11> make 
g++ -o try-catch try-catch.cpp -g -Wall
PS E:\fly-prj\cplusplus\day11> .\try-catch.exe
Division by zero condition!

C++ 标准的异常

在这里插入图片描述

下表是对上面层次结构中出现的每个异常的说明:

异常描述
std::exception该异常是所有标准 C++ 异常的父类。
std::bad_alloc该异常可以通过 new 抛出。
std::bad_cast该异常可以通过 dynamic_cast 抛出。
std::bad_exception这在处理 C++ 程序中无法预期的异常时非常有用。
std::bad_typeid该异常可以通过 typeid 抛出。
std::logic_error理论上可以通过读取代码来检测到的异常。
std::domain_error当使用了一个无效的数学域时,会抛出该异常。
std::invalid_argument当使用了无效的参数时,会抛出该异常。
std::length_error当创建了太长的 std::string 时,会抛出该异常。
std::out_of_range该异常可以通过方法抛出,例如 std::vector 和 std::bitset<>::operator。
std::runtime_error理论上不可以通过读取代码来检测到的异常。
std::overflow_error当发生数学上溢时,会抛出该异常。
std::range_error当尝试存储超出范围的值时,会抛出该异常。
std::underflow_error当发生数学下溢时,会抛出该异常。

定义新的异常

可以通过继承和重载 exception 类来定义新的异常。

实例2:

/*******************************************************************
 *   > File Name: classException.cpp
 *   > Create Time: 2021年09月13日 18:56:53
 ******************************************************************/
#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception
{
    // what() 是异常类提供的一个公共方法,它已被所有子异常类重载。
    // 这将返回异常产生的原因。
    const char * what() const throw()
    {
        return "C++ Exception";
    }
};

int main(void)
{
    try
    {
        throw MyException();
    }
    catch(MyException& e)
    {
        std::cout << "MyException caught" << std::endl;
        std::cout << e.what() << std::endl;
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }
    
    return 0;
}

编译、运行:

PS E:\fly-prj\cplusplus\day11> make
g++ -o classException classException.cpp -g -Wall
PS E:\fly-prj\cplusplus\day11> .\classException.exe
MyException caught
C++ Exception

实例3:

/*******************************************************************
 *   > File Name: classException1.cpp
 *   > Create Time: 2021年09月13日 19:14:54
 ******************************************************************/
#include <iostream>
#include <string>
#include <exception>
using namespace std;

int main(void)
{
    string str = "http://c.biancheng.net";

    try
    {
        char ch1 = str[100];
        cout << ch1 << endl;
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
        std::cout << "[1]out of bound!" << endl;
    }

    try
    {
        char ch2 = str.at(100);
        cout << ch2 << endl;
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
        std::cout << "[2]out of bound!" << endl;
    }

    return 0;
}

编译、运行:

PS E:\fly-prj\cplusplus\day11> make
g++ -o classException1 classException1.cpp -g -Wall
PS E:\fly-prj\cplusplus\day11> .\classException1.exe

basic_string::at: __n (which is 100) >= this->size() (which is 22)
[2]out of bound!

可以看出,第一个 try 没有捕获到异常,输出了一个没有意义的字符(垃圾值)。因为[ ]不会检查下标越界,不会抛出异常,所以即使有错误,try 也检测不到。换句话说,发生异常时必须将异常明确地抛出,try 才能检测到;如果不抛出来,即使有异常 try 也检测不到。所谓抛出异常,就是明确地告诉程序发生了什么错误。

第二个 try 检测到了异常,并交给 catch 处理,执行 catch 中的语句。需要说明的是,异常一旦抛出,会立刻被 try 检测到,并且不会再执行异常点(异常发生位置)后面的语句。本例中抛出异常的位置是 at() 函数,它后面的 cout 语句就不会再被执行,所以看不到它的输出。

说得直接一点,检测到异常后程序的执行流会发生跳转,从异常点跳转到 catch 所在的位置,位于异常点之后的、并且在当前 try 块内的语句就都不会再执行了;即使 catch 语句成功地处理了错误,程序的执行流也不会再回退到异常点,所以这些语句永远都没有执行的机会了。

执行完 catch 块所包含的代码后,程序会继续执行 catch 块后面的代码,就恢复了正常的执行流。

异常的处理流程:

抛出(Throw)--> 检测(Try) --> 捕获(Catch)

实例4:

/*******************************************************************
 *   > File Name: classExceptionFunc.cpp
 *   > Create Time: 2021年09月13日 19:26:53
 ******************************************************************/
#include <iostream>
#include <string>
#include <exception>
using namespace std;

void func(){
    /*  try 块中调用的某个函数中发生了异常 */
    throw "Unkown Exception";
    cout << "[1] This statement will not be executed." << endl;
}

int main(void)
{
    try
    {
        func();
        cout << "[2] This statement will not be executed." << endl;
    }
    catch(const char* &e)
    {
        std::cerr << e << '\n';
        cout << "[3] This statement will be executed." << endl;
    }
    
    return 0;
}

编译、运行:

PS E:\fly-prj\cplusplus\day11> make 
g++ -o classExceptionFunc classExceptionFunc.cpp -g -Wall
PS E:\fly-prj\cplusplus\day11> .\classExceptionFunc.exe
Unkown Exception
[3] This statement will be executed.

实例5:

/*******************************************************************
 *   > File Name: classExceptionFunc1.cpp
 *   > Create Time: 2021年09月13日 19:34:17
 ******************************************************************/
#include <iostream>
#include <string>
#include <exception>
using namespace std;

/*
try 块中调用了某个函数,该函数又调用了另外的一个函数,这个另外的函数抛出了异常:
*/
void func_inner()
{
    throw "Unkown Exception";
    cout << "[1]This statement will not be executed." << endl;
}

void func_outer()
{
    func_inner();
    cout << "[2]This statement will not be executed." << endl;
}

int main(void)
{
    try
    {
        func_outer();
        cout << "[3]This statement will not be executed." <<endl;
    }
    catch(const char* &e)
    {
        std::cerr << e << '\n';
        cout << "[4]This statement will be executed." << endl;
    }

    return 0;
}

编译、运行:

PS E:\fly-prj\cplusplus\day11> make
g++ -o classExceptionFunc1 classExceptionFunc1.cpp -g -Wall
PS E:\fly-prj\cplusplus\day11> .\classExceptionFunc1.exe  
Unkown Exception
[4]This statement will be executed.

catch 在匹配过程中的类型转换

C/C++ 中存在多种多样的类型转换,以普通函数(非模板函数)为例,发生函数调用时,如果实参和形参的类型不是严格匹配,那么会将实参的类型进行适当的转换,以适应形参的类型,这些转换包括:

  • 算数转换:例如 int 转换为 float,char 转换为 int,double 转换为 int 等。
  • 向上转型:也就是派生类向基类的转换,请猛击《C++向上转型(将派生类赋值给基类)》了解详情。
  • const 转换:也即将非 const 类型转换为 const 类型,例如将 char * 转换为 const char *。
  • 数组或函数指针转换:如果函数形参不是引用类型,那么数组名会转换为数组指针,函数名也会转换为函数指针。
  • 用户自定的类型转换

catch 在匹配异常类型的过程中,也会进行类型转换,但是这种转换受到了更多的限制,仅能进行「向上转型」、「const 转换」和「数组或函数指针转换」,其他的都不能应用于 catch。

实例6:

/*******************************************************************
 *   > File Name: classExceptionConst.cpp
 *   > Create Time: 2021年09月13日 19:46:04
 ******************************************************************/
#include <iostream>
using namespace std;

int main(void)
{
    int nums[] = {1, 2, 3};
    try
    {
        throw nums;
        cout << "This statement will not be executed." << endl;
    }
    catch(const int*  &e) /* 引用是为了提高效率。如果不使用引用,就要经历一次对象拷贝(要调用拷贝构造函数)的过程。 */
    {
        std::cerr << "Exception type: const int * " << e << '\n';
    }
    
    return 0;
}

编译、运行:

PS E:\fly-prj\cplusplus\day11> make 
g++ -o classExceptionConst classExceptionConst.cpp -g -Wall
PS E:\fly-prj\cplusplus\day11> .\classExceptionConst.exe
Exception type: const int * 0xffffcbd4

nums 本来的类型是int [3],但是 catch 中没有严格匹配的类型,所以先转换为int *,再转换为const int *

数组也是一种类型,数组并不等价于指针,这点已在《数组和指针绝不等价,数组是另外一种类型》和《数组到底在什么时候会转换为指针》中进行了详细讲解。

C++ throw(抛出异常)详解

C++ throw(抛出异常)详解

C++ exception类:C++标准异常的基类

C++ exception类:C++标准异常的基类

exception 类位于 头文件中,它被声明为:

class exception{
public:
    exception () throw();  //构造函数
    exception (const exception&) throw();  //拷贝构造函数
    exception& operator= (const exception&) throw();  //运算符重载
    virtual ~exception() throw();  //虚析构函数
    virtual const char* what() const throw();  //虚函数
}


这篇关于C++ | C++异常处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程