C++异常是指在程序运行时发生的反常行为,这些行为超出了函数正常功能的范围。当程序的某部分检测到一个它无法处理的问题时,需要用到异常处理。异常提供了一种转移程序控制权的方式。C++异常处理涉及到三个关键字:try、catch、throw。

在C++语言中,异常处理包括:

(1)、throw表达式:异常检测部分使用throw表达式来表示它遇到了无法处理的问题,throw引发了异常。throw表达式包含关键字throw和紧随其后的一个表达式,其中表达式的类型就是抛出的异常类型。throw表达式后面通常紧跟一个分号,从而构成一条表达式语句。

(2)、try语句块:异常处理部分使用try语句块处理异常。try语句块以关键字try开始,并以一个或多个catch子句结束。try语句块中代码抛出的异常通常会被某个catch子句处理。因为catch子句处理异常,所以它们也被称作异常处理代码。catch子句包括三部分:关键字catch、括号内一个(可能未命名的)对象的声明(称作异常声明,exception  declaration)以及一个块。当选中了某个catch子句处理异常之后,执行与之对应的块。catch一旦完成,程序跳转到try语句块最后一个catch子句之后的那条语句继续执行。try语句块声明的变量在块外部无法访问,特别是在catch子句内也无法访问。如果一段程序没有try语句块且发生了异常,系统会调用terminate函数并终止当前程序的执行。

(3)、一套异常类(exception class):用于在throw表达式和相关的catch子句之间传递异常的具体信息。

C++标准库定义了一组类,用于报告标准库函数遇到的问题。这些异常类也可以在用户编写的程序中使用,它们分别定义在4个头文件中:

(1)、exception头文件定义了最通常的异常类exception,它只报告异常的发生,不提供任何额外的信息。

(2)、stdexcept头文件定义了几种常用的异常类,如下(《C++ Primer(Fifth Edition)》):

(3)、new头文件定义了bad_alloc异常类型。

(4)、type_info头文件定义了bad_cast异常类型。

Exceptions provide a way to react to exceptional circumstances (like run time errors) in programs by transferring control to special functions called handlers.

To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing that portion of code in a try-block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.

An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block.

The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called std::exception and is defined in the<exception> header. This class has a virtual member function called what that returns a null-terminated character sequence (of type char *) and that can be overwritten in derived classes to contain some sort of description of the exception.

C++provides a list of standard exceptions defined in <exception> ( https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm ):

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "try_catch.hpp"
#include <iostream>
#include <exception>
#include <vector>//
// reference: http://www.cplusplus.com/doc/tutorial/exceptions/
int test_exception1()
{try {throw 20;}catch (int e) {std::cout << "An exception occurred. Exception Nr. " << e << '\n';}return 0;
}class myexception : public std::exception
{virtual const char* what() const throw(){return "My exception happened";}
} myex;int test_exception2()
{try {throw myex;}catch (std::exception& e) { // catches exception objects by reference (notice the ampersand & after the type)std::cout << e.what() << '\n';}return 0;
}int test_exception3()
{
/*exception     descriptionbad_alloc        thrown by new on allocation failurebad_cast     thrown by dynamic_cast when it fails in a dynamic castbad_exception     thrown by certain dynamic exception specifiersbad_typeid        thrown by typeidbad_function_call   thrown by empty function objectsbad_weak_ptr        thrown by shared_ptr when passed a bad weak_ptr
*/try {int* myarray = new int[1000];}catch (std::exception& e) { // Takes a reference to an 'exception' objectstd::cout << "Standard exception: " << e.what() << std::endl;}return 0;
}///
// reference: http://en.cppreference.com/w/cpp/language/try_catch
int test_exception4()
{try {std::cout << "Throwing an integer exception...\n";throw 42;}catch (int i) {std::cout << " the integer exception was caught, with value: " << i << '\n';}try {std::cout << "Creating a vector of size 5... \n";std::vector<int> v(5);std::cout << "Accessing the 11th element of the vector...\n";std::cout << v.at(10); // vector::at() throws std::out_of_range}catch (const std::exception& e) { // caught by reference to basestd::cout << " a standard exception was caught, with message '"<< e.what() << "'\n";}return 0;
}/
// reference: https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
static int division(int a, int b) {if (b == 0) {throw "Division by zero condition!";}return (a / b);
}int test_exception5()
{int x{ 50 }, y{ 0 }, z{ 0 };try {z = division(x, y);std::cout << z << std::endl;}catch (const char* msg) {std::cerr << msg << std::endl;}return 0;
}struct MyException : public std::exception
{const char * what() const throw () {return "C++ Exception";}
};int test_exception6()
{try {throw MyException();}catch (MyException& e) {std::cout << "MyException caught" << std::endl;std::cout << e.what() << std::endl;}catch (std::exception& e) {//Other errors}return 0;
}int test_exception7()
{try {char* str = nullptr;str = new char[10];if (str == nullptr) throw "Allocation failure";for (int n = 0; n <= 100; n++) {if (n > 9) throw n;str[n] = 'z';}}catch (int i) {std::cout << "Exception: ";std::cout << "index " << i << " is out of range" << std::endl;}catch (char * str) {std::cout << "Exception: " << str << std::endl;}return 0;
}

GitHub:https://github.com/fengbingchun/Messy_Test

C++中try/catch/throw的使用相关推荐

  1. JavaScript中try, catch, throw的用法

    文章出自个人博客https://knightyun.github.io/2019/09/02/js-try,转载请申明. 程序在运行中难免遇到 bug,所以就需要好的调试手段找出问题所在,try, c ...

  2. C#中try catch中throw ex和throw方式抛出异常有何不同

    C#中try catch中throw ex和throw方式抛出异常有何不同 参考文章: (1)C#中try catch中throw ex和throw方式抛出异常有何不同 (2)https://www. ...

  3. 22 C#中的异常处理入门 try catch throw

    22 C#中的异常处理入门 try catch throw 参考文章: (1)22 C#中的异常处理入门 try catch throw (2)https://www.cnblogs.com/thin ...

  4. php try 中 抛出异常处理,php中try catch捕获异常实例详解

    php中try catch可以帮助我们捕获程序代码的异常了,这样我们可以很好的处理一些不必要的错误了,感兴趣的朋友可以一起来看看. PHP中try{}catch{}语句概述 PHP5添加了类似于其它语 ...

  5. php中try catch捕获异常实例详解

    本文实例讲述了php中try catch捕获异常.分享给大家供大家参考.具体方法分析如下: php中try catch可以帮助我们捕获程序代码的异常了,这样我们可以很好的处理一些不必要的错误了,感兴趣 ...

  6. C++异常处理(try catch throw)完全攻略

    C语言中文网推出辅导班啦,包括「C语言辅导班.C++辅导班.算法/数据结构辅导班」,全部都是一对一教学:一对一辅导 + 一对一答疑 + 布置作业 + 项目实践 + 永久学习.QQ在线,随时响应! 程序 ...

  7. C# 异常处理(Catch Throw)IL分析

    1.catch throw的几种形式及性能影响: private void Form1_Click(object sender, EventArgs e){try{}catch{throw;}}pri ...

  8. RuntimeException的特殊情况[C++] 有人会在程序中try catch吗?什么样的问题需要用try catch语句执行

    http://www.bitscn.com/pdb/java/200605/23824.html 本章的第一个例子是: if(t == null) throw new NullPointerExcep ...

  9. 【C到C++】C++中的抛出异常throw 和异常处理try- catch

    全文:http://blog.csdn.net/zzjxiaozi/article/details/6649999 摘选: 1.抛出异常(也称为抛弃异常)即检测是否产生异常,在C++中,其采用thro ...

最新文章

  1. 什么是壳 - 脱壳篇01
  2. (笔试题)小米Git
  3. 在cshtml中显示FCKeditor编辑器控件
  4. 二:Go编程语言规范-类型
  5. Codeforces Round #682 (Div. 2)D Powerful Ksenia ///思维
  6. 剖析:3D游戏建模的千奇百变,带你快速入门
  7. linux下gcc的编译过程详解
  8. micropython 人脸识别检测_Flask实战!从后台管理到人脸识别,六款优质Flask开源项目介绍...
  9. Java游戏程序设计教程 第2章 游戏设计的基本流程
  10. 全国计算机比赛微课视频,“教学之星”全国总决赛 | 冠军朱琦微课及现场比赛视频...
  11. 4个步骤教你建立中后台后台通用权限管理系统
  12. bat脚本打开刷新网页
  13. 使用PHP制作 简易员工管理系统之三(管理员登陆界面以及数据库验证)
  14. 什么是有氧运动?什么是无氧运动?哪个减肥效果更好?
  15. 百度成小满运维面试题
  16. Vue 之 echarts 图表数据可视化的基础使用(简单绘制各种图表、地图)
  17. HTTP协议详解(二)
  18. java kumo生成词云
  19. 移动端网页录音上传,服务端智能语音识别
  20. 服务器内存条能点亮显示器吗,上两根内存条显示器就不亮了

热门文章

  1. Python Qt GUI设计:QSpinBox计数器类(基础篇—15)
  2. 【MediaPipe】(3) AI视觉,人脸识别,附python完整代码
  3. Matlab视频流处理:读取,播放,保存
  4. JAVA Web项目中所出现错误及解决方式合集(不断更新中)
  5. Udacity机器人软件工程师课程笔记(十一)-ROS-编写ROS节点
  6. Udacity机器人软件工程师课程笔记(五)-样本搜索和找回-基于漫游者号模拟器-自主驾驶
  7. ValueError: invalid literal for int() with base 10
  8. squid中的X-Cache和X-Cache-Lookup的意义
  9. mixamo网站FBX模型带骨骼绑定动作库
  10. ZBrush全面入门学习教程 Schoolism – Introduction to ZBrush