c++异常处理

C++异常处理 基于著名书籍和自我学习得出的C++异常处理 阅读详情

1 为什么我们一直强调不能使用返回错误值的方法来代替异常处理?

   看这个例子:

   int add(int a, int b)

   {

        return a+b;

   }

 

   在这里, 我们无法用返回错误值的方法来表示错误. 因为我们无法分辨返回的值是正确计算的结果还是错误码.

 

2  在判断new是否成功时, 我们究竟是用返回值为null来判断还是用std::bad_alloc异常来判断? 当new无法成功分配内存时, 它会即返回null又抛出std::bad_alloc吗? 不会的. 它们或者返回空值, 或者抛出std::bad_alloc.  关于究竟如何对new进行管理, 我参考国下面链接中的文章. http://bytes.com/topic/c/answers/470836-new-bad_alloc-null,  看来看去, 还是没有一个明确的答案, 看来要得到正确还得要自己动手做实验, 我们用下面的代码分别在vc6和vs 2008下运行, 看看能得到什么结果


#include "stdafx.h"
// newexcp.cpp -- the bad_alloc exception
#include <iostream>
using namespace std;
#include <new>
#include <cstdlib>

struct Big
{
    double stuff[2000];
};
int main(int argc, char* argv[])
{
 Big * pb;
    try {
        cout << "Trying to get a big block of memory:/n";
        pb = new Big[100000];
        cout << "Got past the new request:/n";
    }
    catch (bad_alloc & ba)
    {
        cout << "Caught the exception!/n";
       // cout << ba.what() << endl;
        exit(1);
    }
    if (pb != 0)
    {
        pb[0].stuff[0] = 4;
        cout << "success" << endl;
    }
    else
        cout << "pb is null pointer/n";
    delete [] pb;
    return 0;
}

 

在vc6下, 不会抛出异常, 而是返回空值.

 在vs2008下, 会抛出异常, 不会返回空值.

 

如果我们将pb = new Big[100000];
 改为pb = new(std::nothrow) Big[100000];

那么将会返回空值, 而不会抛出异常.

 

3 int add(int a, int b) throw(string ) 代表着该函数会抛出一个string异常.

   int add(int a, int b) throw()           代表着该函数不会抛出任何异常.

 

那么int add(int a, int b)  代表什么? 也是不抛出异常吗?如果是这样的话, throw()岂不是多此一举吗?

 

 

 

 

C++ 异常处理 C++ 异常处理 文章目录C++ 异常处理1. 异常关键字2. 异常处理实例3. C++ 标准异常4. 自定义异常5. 被遗弃的标准 1. 异常关键字 异常是程序在 执行期间 产生的问题。C++ 异常是指在程序运行时发生的特殊情况,比如尝试除以零的操作。 异常提供了一种 转移程序控制权 的方式。 C++ 异常处理涉及到三个关键字:try、catch、throw。 关键字 描述 th... 阅读详情

相关推荐

C++异常处理机制

1、概述 感谢大家,我是假装很努力的YoungYangD(小羊)。 参考资料: 《More Effective C++》

weixin_39640298的博客 2051

PHP-CPP异常处理机制:从C++到PHP的错误传递终极指南

PHP-CPP是一个强大的C++库,它允许开发者创建高效的PHP扩展,将C++的性能优势与PHP的灵活性完美结合。在开发PHP扩展时,异常处理是确保代码健壮性和可靠性的关键环节。本文将深入探讨PHP-CPP的异常处理机制,从C++异常的抛出到PHP错误的传递,为你提供一套完整的错误处理解决方案。 ## 🧩 PHP-CPP异常体系核心组件 PHP-CPP提供了一套完善的异常处理体系,主要包含以

gitblog_00507的博客 539

基于计算机视觉的Windows自动化工具openclaw-win:从原理到实战

计算机视觉与自动化技术正深刻改变人机交互方式,其核心在于让机器具备“感知-决策-执行”的能力。通过图像采集与处理算法,程序可以识别屏幕上的特定元素;结合模拟输入技术,便能自动执行点击、拖拽等操作,形成完整的自动化闭环。这一技术栈在软件测试、数据采集、重复性办公任务等领域具有重要价值,能够显著提升工作效率。开源项目openclaw-win正是这一理念的工程实践,它整合了图像识别与模拟操作模块,为开发者提供了一个研究自动化技术的具体样本。项目涉及模板匹配、坐标计算等关键技术点,并需处理屏幕适配、操作延迟等实际问

weixin_28745975的博客 331

Cpp_异常处理

一、为什么需要异常?1.程序不可能不出错2.传统的错误处理机制存在缺陷 1)通过返回值表示错误 缺点:错误处理流程比较复杂,逐层判断,代码臃肿。 优点:函数调用路径中所有的局部对象(栈对象)都能被右花括号正确地析构,不会内存泄漏。 2)通过远程跳转处理错误优点:不需要逐层判断,一步到位处理错误,代码精炼。 缺点:函数调用路径中的局部对象失去被析构机会,形成内存泄漏。3.C++的异常结合两种

Jerry的专栏 2502

高通ISP模块全解析:从Raw到JPEG的18个关键处理步骤(附避坑指南)

本文全面解析高通ISP模块从Raw到JPEG的18个关键处理步骤,涵盖原始数据预处理、色彩科学处理链、画质增强与降噪等核心环节。通过实战调优经验,揭示ISP架构中的技术原理与工程实践要点,帮助开发者避免常见问题,提升移动影像处理质量。

weixin_30399155的博客 359

微带线贴片天线尺寸的计算,利用Matlab计算+常见的RF计算在线公式

微带线贴片天线尺寸的计算,利用Malatb计算 这几天在使用hfss对矩形天线仿真,每次改变频率和实验的材料,都要重新计算一遍,太麻烦了,所以用matlab进行计算。 知道天线的工作频率:f_r 介质板的介电常数:epsilon_r 介质板厚度:h 就可以计算出矩形天线的长:L 矩形天线的宽:W 对于下面公式的单位要注意,公式以及化简了,要注意单位 由于matlab中的变量不能用希腊字母代替,所以用了该字母的读音 代码如下: f_r=2.45; %工作频率,单位GHz epsilon_r=3.5;

weixin_43404609的博客 2万+

C++的异常处理

一、什么是异常处理        一句话:异常处理就是处理程序中的错误。二、为什么需要异常处理,以及异常处理的基本思想        C++之父Bjarne Stroustrup在《The C++ Programming Language》中讲到:一个库的作者可以检测出发生了运行时错误,但一般不知道怎样去处理它们(因为和用户具体的应用有关);另一方面,库的用户知道怎样处理这些错误,但却

大黑暗天 的专栏 2万+

超速U盘选购避坑指南:如何通过Rx Detect机制识别真伪USB3.0设备

本文深入解析了USB 3.0超速U盘的选购避坑要点,重点介绍了通过Rx Detect机制识别真伪设备的核心原理。文章提供了从软件检测到实际性能测试的完整方案,帮助消费者和技术人员有效辨别虚假的USB3.0设备,确保获得真正的超速传输体验。

weixin_29189373的博客 445

【c++】异常处理

当程序在运行过程中出现问题,没有达到理想效果时,异常可以帮助我们对这些问题进行通信并做出相应的处理,将问题的检测与解决问题的过程分离开,更好地应对大型项目可能出现的各种情况。相比于C语言处理错误的方式--返回错误码,我们在c++中,遇到异常时可以抛出一个对象,该对象所携带的错误信息可以更加全面。本篇文章,我们主要学习了异常的使用方法及其处理机制。相比c语言错误码的方式,c++的异常可以更加全面地处理程序出现的问题。但异常也有些缺点,例如造成程序执行混乱,内存泄漏等等。

2301_80955819的博客 1658

向量数据库安全实战:从Embedding反推到检索越权的全链路防护

随着RAG应用在企业中的普及,向量数据库已成为知识库系统的核心组件。但许多团队对向量数据的安全认知仍停留在传统数据库的账号密码、网络隔离和磁盘加密上。事实上,向量化并非加密,而是一种有损压缩的语义映射,向量本身可以被反推模型还原出原文关键信息,形成高保真的语义泄露通道。同时,相似度检索的模糊匹配特性打破了传统行列权限模型,使得越权检索和成员推断攻击成为新的安全威胁。理解这些原理,有助于企业在数据采集、向量化、索引构建、检索查询等环节构建分层防护体系,包括脱敏、扰动、过滤下推、网关控制等手段。本文从基础概念出

weixin_29323551的博客 259

2023华为od机试C卷【最富裕的小家庭】Python 实现

在一颗树中,每个节点代表一个家庭成员,节点的数字表示其个人的财富值,一个节点及其直接相连的子节点被定义为个小家庭。现给你一颗树,请计算出最富裕的小家庭的财富和。

MISAYAONE的博客 2044

Cpp(六) 异常处理Exception

文章目录C++ 异常处理#1 环境#2 开始#2.1 格式#2.2 异常类型#2.3 自定义异常 C++ 异常处理 #1 环境 C++14 CMake 3.17 macOS 10.15.5 Clion #2 开始 #2.1 格式 格式: try{ // 抛异常 throw ExceptionType("xxx"); }catch( ExceptionType1 e1 ){ // ExceptionType1异常 // 异常处理 }catch( ExceptionType2 e2

Auto 1623

【数字IC/FPGA】低功耗设计

低功耗设计方法功耗的类型低功耗设计方法静态低功耗技术多阈值工艺方法电源门控方法体偏置动态低功耗技术多电压域(Multi-Voltage Domain)预计算门控时钟门级优化技术毛刺的消除逻辑级优化物理级优化控制输入向量低功耗Soc系统的动态管理动态电压及频率调节技术低功耗操作系统存储器功耗控制总结 功耗的类型 CMOS电路中的功耗由两部分构成,第一部分为负载电容充放电时引起的功耗,称为动态功耗,另一部分为漏电流引起的功耗,称为静态功耗。其中动态功耗包括翻转功耗和短路功耗。翻转功耗是数字电路中信号翻转时电容充

qq_40268672的博客 3072

I异常处理.cpp

本文深入浅出地讲解了 C++ 异常处理机制,涵盖 try - catch - throw 的基本用法、常见异常类型,并通过文件读取和电商订单系统案例,展示如何在实战中优雅应对各种错误场景。同时强调异常处理对程序健壮性、用户体验、资源管理及代码可维护性的重要性,助你掌握这一编程 “利器”。

m0_66709139的博客 1201

CAN轴控制流【6041,6040】

【代码】CAN轴控制流【6041,6040】

cfqq1989的博客 1783

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

C++异常处理完全指南:CPP-Crash-Course中的错误处理最佳实践

C++异常处理是现代C++开发中不可或缺的错误处理机制,本指南将从CPP-Crash-Course项目出发,详细介绍异常处理的核心概念、使用方法和最佳实践,帮助开发者构建更健壮的C++应用程序。 ## 为什么异常处理对C++开发至关重要 在C++程序开发过程中,错误处理是保证程序稳定性和可靠性的关键环节。传统的错误码返回方式存在诸多局限,而异常处理机制提供了一种更优雅、更灵活的错误处理方案。C

gitblog_00521的博客 799

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

C++ 异常处理总结

一、 参考文献: 【1】C++异常处理:https://www.runoob.com/cplusplus/cpp-exceptions-handling.html

灰太狼的小秘密 3701

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

c和cpp的异常处理

try-catch`结构是用于异常处理的,并且通常是在C++或其他高级语言中使用。在C语言中,异常处理通常通过返回错误代码和使用`setjmp`和`longjmp`函数来实现。在这个例子中,`setjmp`用于保存当前的执行环境,如果调用`longjmp`,则程序会返回到`setjmp`的调用点,并从那里继续执行。这种方法可以模拟类似`try-catch`的行为,但需要手动管理。在C++中,`try-catch`语句用于异常处理。- 如果没有匹配的`catch`块,程序将终止。

cocofu的博客 597

【C++】异常处理

关于C++中的异常

2303_80828380的博客 1546

异常处理.cpp

// 异常处理.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "异常处理.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #

autumn20080101的专栏 734

告别崩溃!cpp-httplib异常处理完全指南

你是否曾因HTTP请求超时导致程序崩溃?是否遇到过证书验证失败却无从调试的情况?cpp-httplib作为轻量级C++ HTTP库,其异常处理机制直接影响程序稳定性。本文将系统解析cpp-httplib的错误处理体系,提供从超时控制到SSL验证的全方位解决方案,让你的网络应用从此稳健运行。 ## 异常处理核心机制 cpp-httplib采用**状态码+错误回调**的双层处理架构,所有异常通过预...

gitblog_00873的博客 626
上一篇: 创建frame/view
下一篇: unit test(UT)
keepdoingit
博客等级 码龄17年 27粉丝 63原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值