Handling Errors Exceptionally Well in C++ 在C++中良好地捕获意外的错误

Handling Errors Exceptionally Well in C++
在C++中良好地捕获意外的错误

from:http://www.cprogramming.com/tutorial/exceptions.html
author:unknown
翻译:范晨鹏
One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected circumstance that the section of code containing the problem is not explicitly designed to handle. In C++, exception handling is useful because it makes it easy to separate the error handling code from the code written to handle the chores of the program. Doing so makes reading and writing the code easier.
C++的一个特性是它的异常捕获系统。异常 是程序的一个未曾预料到的环节,没有代码被明确地设计用来处理包含问题的代码片断。在C++中,异常处理是非常有用的。因为它使得错误处理代码从程序的正常代码中分离出来。从而使得代码容易书写并便于阅读。
Furthermore, exception handling in C++ propagates the exceptions up the stack; therefore, if there are several functions called, but only one function that needs to reliably deal with errors, the method C++ uses to handle exceptions means that it can easily handle those exceptions without any code in the intermediate functions. One consequence is that functions don't need to return error codes, freeing their return values for program logic.
而且,C++的异常捕获一直传达到栈中。因此,如果有一系列的函数调用,但是仅有一个函数需要进行错误处理,C++中使用的异常捕获意味着它可以很容易地来处理那些异常,而不需要在函数内部书写专门的代码。其影响是:函数不需要返回错误代码,这为程序逻辑解放了它们的返回值。

When errors occur, the function generating the error can 'throw' an exception. For example, take a sample function that does division:
错误发生的时候,产生错误的函数会“抛出”一个异常。以一个做除法运算的函数为例来说明:

const int DivideByZero = 10;
//....
double divide(double x, double y)
{
    if(y==0)
    {
        throw DivideByZero;
    }
    return x/y;
}



The function will throw DivideByZero as an exception that can then be caught by an exception-handling catch statement that catches exceptions of type int. The necessary construction for catching exceptions is a try catch system. If you wish to have your program check for exceptions, you must enclose the code that may have exceptions thrown in a try block. For example:
这个函数会返回“除数为0”的错误。这个异常随后会被专门捕获int型异常的异常捕获语句捕获。捕获异常必须的构件是一个try catch系统。如果你希望你的程序接收异常检查,你必须将可能有异常捕获的代码包含在一个try块中。例如:
try
{
    divide(10, 0);
}
catch(int i)
{
    if(i==DivideByZero)
    {
        cerr<<"Divide by zero error";
    }
}


The catch statement catches exceptions that are of the proper type. You can, for example, throw objects of a class to differentiate between several different exceptions. As well, once a catch statement is executed, the program continues to run from the end of the catch.
catch
catch语句捕获特定类型的异常。例如,你可以抛出一个类的几个对象来区分一些不同的异常。同时,一旦执行了一个catch语句,程序会从catch块的后面继续执行。
It is often more useful for you to create a class that stores information on exceptions as they occur. For example, it would be more useful if you had a class to handle exceptions.

创建一个类来保存错误发生时的信息是常常是很有用的。例如,如果你用一个类来处理异常:

class DivideByZero
{
    public:
        double divisor;
        DivideByZero(double x);
};
DivideByZero::DivideByZero(double x) : divisor(x)
{}
int divide(int x, int y)
{
    if(y==0)
    {
        throw DivideByZero(x);
    }
}
try
{
    divide(12, 0);
}
catch (DivideByZero divZero)
{
    cerr<<"Attempted to divide "<<divZero.divisor<<" by zero";
}
f you wish to catch more than one possible exception, you can specify separate catch blocks for each type of exception. It's also possible to have a general exception handler that will respond to any thrown exception. To use it, simply use catch(...) for the catch statement and print a general warning of some kind.
如果你想捕获超过一个可能的异常,你可以为每个类型的异常指定独立的catch块。还可用一个通用的异常句柄来响应抛出的任何异常。要使用它,只需要为catch语句使用catch(...)来打印一个通用的警告语句或使用类似的处理方式。
The handy thing to remember about exception handling is that the errors can be handled outside of the regular code. This means that it is easier to structure the program code, and it makes dealing with errors more centralized. Finally, because the exception is passed back up the stack of calling functions, you can handle errors at any place you choose.
关于异常捕获顺便要提及的是:错误可以在正常代码之外被处理。这意味着很容易实现结构化的程序代码,而且它使得错误处理更集中。最后,因为异常被传回一直到主调函数的栈,你可以在(被调用函数)的任何地方捕获错误。
In C, you might see some error handling code to free memory and close files repeated five or or six times, once for each possible error. A solution some programmers prefered was to use a goto statement that jumped all the way to the cleanup code. Now, you can just surround your code with a try-catch block and handle any cleanup following the catch (possibly with an additional copy of your cleanup routine inside the catch block if you intend to throw the exception again to alert the calling function of an error).
在C中,你可能会看到一些错误捕获代码,这些代码用来释放内存和关闭文件。它们被重复若干次,在每一个可能发生错误的地方。一些程序员偏爱的一种解决方法是使用goto语句。goto语句可以直接跳到执行清除操作的代码部分。现在,你可以仅仅把你的代码包围在一个try-catch块中并在catch之后执行一个清除操作。(可能要在catch块中保存你的清理机制的一份拷备,如果你愿意将异常再次抛出以通知主调函数一个错误。)

转载于:https://www.cnblogs.com/diylab/archive/2007/09/05/883533.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/269204.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MFC 使用 Picture control 显示图片和数据流

一、使用现有的图片文件显示在 界面 picture 控件 在MFC picture 加载bitmap 图片方法图片可以是从资源文件夹来的&#xff0c;也可以是文件路径等CBitMap 载入图像接口 有两种方式 BOOL LoadBitmap(LPCTSTR lpszResourceName); // 资源文件名 BOOL LoadBitmap(UINT nIDResour…

MFC 对话框添加重写初始化对话框函数来设置界面

BOOL MyVideo::OnInitDialog() {CDialogEx::OnInitDialog(); // 调用父类// TODO: 在此添加额外的初始化imageScaleValue.SetCurSel(0);imageScaleValue.AddString(_T("1"));imageScaleValue.AddString(_T("2"));imageScaleValue.AddString(_T("3&qu…

OSPF动态路由协议入门简介

——随着Internet技术在全球范围的飞速发展&#xff0c;OSPF已成为目前Internet广域网和Intranet企业网采用最多、应用最广泛的路由协议之一。OSPF&#xff08;Open Shortest Path First&#xff09;路由协议是由IETF&#xff08;Internet Engineering Task Force&#xff09;I…

linux磁盘冗余阵列

RAID防止硬盘物理损坏以及增加存储设备的吞吐量&#xff0c;RAID常见的组合有0、1、5、和10RAID0:至少需要两块硬盘&#xff0c;可以有效提高硬盘的性能和吞吐量&#xff0c;但没有数据的冗余和错误修复能力将多块硬盘通过硬件或软件的方式串联在一起&#xff0c;成为一个大的卷…

关于管理的经典故事(员工激励)

员工管理和激励是一个复杂的事情&#xff0c;有时让管理者摸不着头脑&#xff0c;甚至感到头疼。销售管理往往并非现场管理&#xff0c;遥控管理无形之中增加了管理的难度。轻松一下&#xff0c;看看以下的十个经典故事&#xff0c;也许你会领略到管理的另一种意境。 一、 分工…

解决 413 Request Entity Too Large(请求实体太大)

今天做上传视频&#xff0c;报错413 Request Entity Too Large 我们可以看到请求的body的大小&#xff0c;在Content-Length后显示&#xff0c;Nginx默认的request body为1M&#xff0c;小于我们上传的大小 解决方案 找到自己主机的nginx.conf配置文件&#xff0c;打开 在http…

YUV422 转换成 RGB

#define CLIPVALUE(x, minValue, maxValue) ((x) < (minValue) ? (minValue) : ((x) > (maxValue) ? (maxValue) : (x))) #define YUVToR(Y, U, V) ( (Y) 1.4075 * ((V) - 128) ) #define YUVToG(Y, U, V) ( (Y) - 0.3455 * ((U) - 128) - 0.7169 * ((V) - 128) ) #de…

带参数的方法

1.语法&#xff1a; <访问修饰符>放回值类型<方法名><(形式方法列表)>{ //方法的主体 } 2.调用带参方法 语法&#xff1a;对象名.方法名&#xff08;参数1&#xff0c;参数2.....参数N&#xff09; 转载于:https://www.cnblogs.com/zyani/p/6…

【oracle灾备方案系列】基于DDS的Oracle复制容灾方案(三)

<?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office" />【oracle灾备方案系列】基于DDS的Oracle灾备方案&#xff08;三&#xff09;1. 数据查询应用平台方案1.1. 构建企业的第二数据中心在基于DataGrid DDS产品实现灾备架构中&am…

MFC 让界面点击无效

把 Disableed 设置为 True 就是让界面不再接受鼠标等控制。

关于 There is no getter for property named ‘id‘ in ‘class java.lang.Integer‘

errMsgorg.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named parentId in class java.lang.Integer 加上 Param("")注解

HTML5录音控件

最近的项目又需要用到录音&#xff0c;年前有过调研&#xff0c;再次翻出来使用&#xff0c;这里做一个记录。 HTML5提供了录音支持&#xff0c;因此可以方便使用HTML5来录音&#xff0c;来实现录音、语音识别等功能&#xff0c;语音开发必备。但是ES标准提供的API并不人性化&a…

关闭 MFC 界面程序控制台输出窗口

MFC 界面控制台界面窗口&#xff0c;在运行程序的时候会弹出来&#xff0c; 为了调试可以显示输出 printf 或 cout 信息&#xff0c;要关闭的话在程序入口处添加freeconsole() 函数进行设置。 避免多个窗口显示影响操作 CMainFrame::CMainFrame() {// TODO: 在此添加成员初始化…

SVN更新的时候报断言失败解决办法

解决办法&#xff1a;没啥好方法&#xff0c;重新检出代码就好使了。 转载于:https://www.cnblogs.com/yuanchaoyong/p/6999496.html

高德 ASIC 256 模组快门状态实时获取方案

1、快门状态命令 这个状态是由 ASIC 程序操作快门后记录的&#xff0c;如果是断电下的意外振动关闭是无法记录的 2、快门状态获取解决办法 根据快门闭合后的特征: 1) 温度均匀&#xff0c; 目标物体温度基本等于快门温度 2) 图像无轮廓线条和角点 3、快门状态实时检测线程 实…

C#委托

委托是一种引用方法的类型。委托定义出它想要代表的方法的原型&#xff0c;然后它可以和任何符合它所定义的方法的原型相关联。但使用委托时就犹如你在调用一个方法。委托使你动态的调用方法变成可能。而动态调用方法的意义就在于你可以在任意的地方插入任意的代码//using Syst…

JS 倒计时插件

剩余时间 <span class"djtime"><i id"t_h"></i><span>:</span><i id"t_m"></i><span>:</span><i id"t_s"></i></span></span> <script type"…