C++中的异常处理

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

1 C++中的异常处理基础

1.1 C++中异常处理简介

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

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

在这里插入图片描述

C++中通过throw语句抛出异常:
在这里插入图片描述
C++异常处理分析:
throw抛出的异常必须被catch处理:

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

在这里插入图片描述
编程实验:C++异常处理初探

#include <iostream>
#include <string>

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;
}


1.2 异常类型匹配

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

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

异常处理的匹配规则:
在这里插入图片描述
编程实验:异常类型匹配

#include <iostream>
#include <string>

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("D.T.Software");
}

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;
}


1.3 异常处理的另一种写法

异常处理还可以写成如下形式:

  • try…catch用于分割正常功能代码与异常处理代码。
  • try…catch可以直接将函数实现分割为2部分。
    在这里插入图片描述

1.4 异常被处理后局部对象的析构函数会被调用吗

看如下代码:

#include <iostream>
#include <string>

using namespace std;

class Animal
{
public:
	Animal()
	{
		cout << "Animal()" << endl;
	}

	~Animal()
	{
		cout << "~Animal()" << endl;
	}
};


void demo()
{
	Animal a;

	throw 0;
}


int main()
{
	try
	{
		demo();
	}
	catch (...)
	{
		cout << "...";
	}
	

	return 0;
}

输出结果如下:
在这里插入图片描述
但是如果不捕捉异常的话,就不会调用抛出异常前的局部对象的析构函数。


2 异常的二次抛出

2.1 catch中抛出基本类型异常

catch语句块中可以抛出异常:
在这里插入图片描述
catch中捕获的异常可以被重新解释后抛出,工程中使用这样的方式统一异常类型。

在这里插入图片描述
编程实验:异常的重新解释

#include <iostream>
#include <string>

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;
    }
}


/*
    假设: 当前的函数式第三方库中的函数,因此,我们无法修改源代码
    
    函数名: 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[])
{
    // Demo();
    
    try
    {
        MyFunc(11);
    }
    catch(const char* cs)
    {
        cout << "Exception Info: " << cs << endl;
    }
    
    return 0;
}


2.2 catch中抛出自定义类型异常

catch中可以抛出自定义类型异常:

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

自定义异常类型的作用:

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

编程实验:类类型的异常

#include <iostream>
#include <string>

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;
}



3 标准库中的异常

C++标准库中提供了实用的异常类族:

  • 标准库中的异常都是从exception类派生的。
  • exception类有两个主要的分支:
    • logic_error:常用于程序中的可避免逻辑错误。
    • runtime_error:常用于程序中无法避免的恶性错误。

标准库中的异常:
在这里插入图片描述


4 terminate函数

先思考一个问题:如果在main函数抛出异常会发生什么?并且这个异常不进行处理,最后会传到哪里?
在这里插入图片描述

下面的代码输出什么?
在这里插入图片描述
输出“Test()”后程序运行结束,不同的平台输出的字符串不同,Windows平台会弹出程序异常的对话框。

异常的最终处理者:

  • 如果异常无法被处理,terminate()结束函数会被自动调用,结束整个程序。terminate()是整个程序释放系统资源的最后机会。
  • 默认情况下,terminate()调用库函数abort()终止程序。
  • abort()函数使得程序执行异常而立即退出。
  • C++支持替换默认的terminate()函数实现。

terminate()函数的替换:
自定义一个无返回值无参数的函数:

  • 不能抛出任何异常。
  • 必须以某种方式结束当前程序。

调用set_terminate(0设置自定义的结束函数:

  • 参数类型为void(*)()。
  • 返回值为默认的terminate()函数入口地址。

编程实验:自定义结束函数

#include <iostream>
#include <cstdlib>
#include <exception>

using namespace std;

void my_terminate()
{
    cout << "void my_terminate()" << endl;
    exit(1);	//调用exit函数会确保所有的全局对象和静态局部对象的析构函数被调用,abort()函数不会
}

class Test 
{
public:
    Test() 
    {
        cout << "Test()"; 
        cout << endl;
    }
	
    ~Test() 
    {
        cout << "~Test()"; 
        cout << endl;
    }
};


int main()
{
    set_terminate(my_terminate);
    
    static Test t;
    
    throw 1;
	
    return 0;
}


5 函数的异常规格说明

思考一个问题:如何判断一个函数是否会抛出异常,以及抛出哪些异常?

函数的异常规格说明:

  • C++提供语法用于声明函数所抛出的异常。
  • 异常声明作为函数声明的修饰符,写在参数列表后面。

在这里插入图片描述
异常规格说明的意义:

  • 提示函数调用者必须做好异常处理的准备。
  • 提示函数的维护者不要抛出其他异常。
  • 异常规格说明是函数接口的一部分。
  • 函数声明和实现处都要写好上相同的规格声明。

问题:如果抛出的异常不在声明列表中中,会发生什么?
在这里插入图片描述
如上的代码,对于g++和bcc编译器,程序直接终止运行,而vs编译器则以char类型的异常捕获。

抛出的异常不在规格说明中:

  • 函数抛出的异常不在规格说明中,全局unexpected()函数被调用。
  • 默认的unexpected()函数会调用全局的terminate()函数。
  • 可以自定义函数替换默认的unexpected()函数实现。
  • 注意:不是所有的C++编译器都支持这个标准行为。

unexpected()函数的替换:
自定义一个无返回值无参数的函数:

  • 能够再次抛出异常:
    • 当异常符合触发函数的异常规格说明时,恢复程序执行。
    • 否则,调用全局terminate()函数结束程序。
  • 调用set_unecpected()设置自定义的异常函数:
    • 参数类型为void(*)()。
    • 返回值为默认的unexceptd()函数入口地址。

编程实验:自定义unexpected()函数

#include <iostream>
#include <cstdlib>
#include <exception>

using namespace std;

void my_unexpected()
{
    cout << "void my_unexpected()" << endl;
    // exit(1);
    throw 1;
}

void func() throw(int)
{
    cout << "func()";
    cout << endl;
    
    throw 'c';
}

int main()
{
    set_unexpected(my_unexpected);
    
    try 
    {
        func();
    } 
    catch(int) 
    {
        cout << "catch(int)";
        cout << endl;
    } 
    catch(char) 
    {
        cout << "catch(char)";
        cout << endl;
    }

    return 0;
}

6 异常的生命周期

对于我们在各个地方抛出的异常,实际上都是抛出了一个匿名变量,不管是基本类型,还是自定义类型。这个匿名变量的生命周期出了cathc语句块就会结束。

对于如下几种形式:

int a = 0;
throw a;	// 实际上会生成一个匿名的临时变量

throw 1;	// 直接是匿名的临时变量

throw Exception();	// 生成匿名对象

Exception e;
throw e;	// 会生成匿名对象,对e进行拷贝

对于如下代码:

#include <iostream>

using namespace std;


class Exception
{
public:
	Exception()
	{
		cout << "Exception() : " << this << endl;
	}

	Exception(const Exception& obj)
	{
		cout << "Exception(const Exception& obj) : " << this << endl;
	}

	~Exception()
	{
		cout << "~Exception() : " << this << endl;
	}
};

void test36()
{
	int a = 123;

	try
	{
		throw Exception();
	}
	catch (const Exception& e)
	{
		cout << "&e : " << &e << endl;
	}
}

输出结果为:
在这里插入图片描述


参考资料:

  1. C++深度解析教程
ubuntu安装hodoop详细步骤 进入到Ubuntu系统中打开桌面,点击鼠标右键打开终端,在终端中输入如下命令这样就可以创建一名为hadoop的新用户。给用户输设置密码输入,输入如下命令,设置密码,按提示输入两次然后为hadoop用户增加管理员全新,这样就可以方便部署完成之后输入重启命令,重启一下Ubuntu系统,然后登录到我们创建的hadoop用户上面reboot。 阅读详情

相关推荐

USB的24脚和12脚TYPEC引脚定义

USB 是一种接口,用于将设备连接到计算机上。通过该连接,计算机可以向设备发送数据或检索来自设备的数据。USB 为开发者提供了一个标准接口,适用于多种不同类型的应用。借助于系统的设计过程,USB 设备易于连接和使用。本应用笔记会使该过程变得更加简单。以下是本应用笔记中会使用的概念:USB 历史USB 架构USB 物理接口USB 速度USB 电源USB 端点USB 通信协议USB 描述符USB 类设备USB 枚举与配置过程。

易板 1万+

C++ 异常处理

C++标准库当中的异常也是一个基础体系,其中exception就是各个异常类的基类,我们可以在程序中使用这些标准的异常,它们之间的继承关系如下:std::exception 该异常是所有标准C++异常的父类。std::bad_alloc 该异常可以通过new抛出。std::bad_cast 该异常可以通过dynamic_cast抛出。std::bad_exception 这在处理C++程序中无法预期的异常时非常有用。

风间琉璃的博客 8721

编译原理2024期末复习(面向做题,大题速学)【太原理工大学】

归约-归约”冲突就是在项目集规范族一个状态中两个。

m0_63181421的博客 1万+

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

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

gitblog_00521的博客 799

S32K144 ADC硬件触发实战:PDB与TRGMUX配置避坑指南

本文深入解析了S32K144微控制器中ADC硬件触发的两种核心方案:PDB与TRGMUX。通过对比其架构差异、详细配置流程及常见问题排查,提供了从寄存器操作到DMA联动的完整优化指南,旨在帮助开发者解决多通道采样时序不稳、CPU负载过高等实际难题,实现高效稳定的数据采集。

weixin_29168153的博客 446

使用Mask2Former和X-Decoder训练自定义数据集及结果复现报告

本报告记录了使用MMDetection框架中的Mask2Former和X-Decoder模型在自定义数据集上的训练过程。报告包含环境配置、数据集准备、模型训练与优化(解决了Mask2Former的PQ值异常问题)、性能评估等关键环节。详细展示了从数据集转换(将客户提供的COCO格式数据适配MMDetection框架)、配置文件修改、到最终模型训练和评估的全流程。特别针对Mask2Former训练中的PQ值异常问题提供了解决方案,并对比了两种模型在自定义数据集上的表现。报告还包含完整的代码实现和技术细节。

huanghm88的专栏 1114

深入理解C++中的异常处理机制

深入理解C++中的异常处理机制异常处理增强错误恢复能力是提高代码健壮性的最有力的途径之一,C语言中采用的错误处理方法被认为是紧耦合的,函数的使用者必须在非常靠近函数调用的地方编写错误处理代码,这样会使得其变得笨拙和难以使用。C++中引入了异常处理机制,这是C++的主要特征之一,是考虑问题和处理错误的一种更好的方式。使用错误处理可以带来一些优点,如下: 错误处理代码的编写不再冗长乏味,并且不再和正常的

zyfforlinux 1万+

一个非常简单的变分量子分类器 (VQC)

​ 在之前的帖子(这里和这里)中,我已经开始谈论 QML,为什么以及如何学习,从现在开始,我将开始分享我的研究和发现,到目前为止,这些都是非常基本的。​

gongdiwudu的专栏 6210

C++中的异常处理方式

在C++中,异常是程序运行期间发生的意外或错误情况。这些情况可能会导致程序无法继续正常执行,但又不能在当前的代码位置立即处理。异常提供了一种机制,使得在错误发生时可以将控制权从当前代码的执行位置转移到异常处理代码的位置,从而进行适当的处理。

decade777555的博客 1854

【Ranger】mac下Apache Ranger编译安装

a、编译过程中出现测试用例不通过和文件认证错误错误:带上参数-DskipTests=true -Drat.skip=true 重新编译;b、若编译过程中出现缺少jar包的情况,可能下载不了,需要手动自动添加;c、编译所需的其他工具如maven等安装配置略。采用这个会报错,因此我才用了下面一个命令。初始化设置Ranger Admin:执行。然后进入target目录。

九师兄 2108

6、深入解析Microsoft 365核心服务对比与迁移策略

本文深入解析了Microsoft 365的核心服务,包括身份和设备管理、现代设备配置体验、Exchange和SharePoint的迁移策略以及Microsoft Teams的协作功能。同时探讨了迁移过程中需要考虑的安全控制措施,为组织规划和实施云迁移项目提供了全面的指导和建议。

k8s6orchestrator的博客 109

c++中的异常处理

您可以通过继承和重载 exception 类来定义新的异常。} };try {//其他的错误 } }

Lyajpunov的博客 1736

黑猫带你学UFS协议第12篇:UFS标志(Flags)和属性(Atrributes)详解

UFS中的标志其实就是一些开关,布尔型,非0即1,打开或者关闭。这些标志可以用来使能或者禁止UFS设备的一些功能、模式或者状态。 简单来说,flag和attribute、discriptor一样,都是ufs的寄存器罢了。只不过spec将这些寄存器分类了,分成这三种大的类型了而已。 标志可以被清除、复位、设置、触发、读。 主机也是通过设备管理器的Query Request UPIU来读取或者写标志。

黑猫奥利奥的博客 2086

Visual C++中的异常处理浅析

Visual C++中的异常处理浅析2005-10-19 09:59作者:宋宝华出处:天极网责任编辑:方舟  4.结构化异常处理  结构化异常处理(Structured Exception Handling,简称SEH)是微软针对Windows程序异常处理进行的扩展,在Visual C++中,它同时支持C和C++语言。SEH不宜与标准C++异常处理和MFC异常处理混用,

Jingle的专栏 925

深度学习工具包 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")

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

C 与C++中的异常处理

C 与C++中的异常处理Robert Schmidt 著无情 译目 录1. 异常和标准C 对它的支持...............................................................................................22. Microsoft 对异常处理方法的扩展...............................

ivan240的专栏 1810

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

C++中的异常处理机制

C++中的异常处理机制一、C++异常处理基本语法二、能够捕获任何异常的 catch 语句三、异常的再拋出四、函数的异常声明列表五、C++标准异常类5.1、bad_typeid5.2、bad_cast5.3、bad_alloc5.4、 out_of_range 一、C++异常处理基本语法 C++ 通过 throw 语句和 try…catch 语句实现对异常的处理。throw 语句的语法如下: throw 表达式; 该语句拋出一个异常。异常是一个表达式,其值的类型可以是基本类型,也可以是类。 try…cat

qq_36721032的博客 758

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

C和C++中的异常处理

1.     简介简介 许多的编程新手对异常处理视而不见,程序里很少考虑异常情况。一部分人甚至根本就不考虑,以为程序总是能以正确的途径运行。譬如我们有的程序设计者调用fopen打开一个文件后,立马就开始进行读写操作,根本就不考虑文件是否正常打开了。在编程过程中恰当地使用异常处理可以增强软件的健壮性。本文将介绍C和C++对于异常处理的一些常用方法。 2.     C语言异常处理 2.1 无条件

August_1989 3490

【C++】一文读懂C++中的异常处理机制

程序有时会遇到运行阶段错误,导致程序无法正常地运行下去。例如,程序可能试图打开一个不可用的文件,请求过多的内存,或者遭遇不能容忍的值。通常,程序员都会试图预防这种意外情况。C++异常为处理这种情况提供了一种功能强大而灵活的工具。对于上述表达式,如果y是x的负值,则上述公式将导致被零除——一种不允许的运算。对于被零除的情况,很多新式编译器通过生成一个表示无穷大的特殊浮点值来处理,cout将这种值显示为Inf、inf、INF或类似的东西;而其他的编译器可能生成在发生被零除时崩溃的程序。

Friday 2338

【C++】C++中的异常处理try-catch

const char *what() const throw(int) //throw(int)表明该函数会抛出整型异常。const char *what() const throw(…) //throw(…)表明该函数会抛出任意类型的异常。//throw(int,double)表明该函数会抛出整型或者double类型异常。//函数不会抛出任何异常,C++11新增。//throw()表明该函数不会抛出异常,新的写法用noexcept来代替。throw 异常类的对象。第二种:抛类类型的异常。

qq_62917398的博客 691
上一篇: C语言中的异常处理
下一篇: C++中的类型识别
SlowIsFastLemon
博客等级 码龄8年 265粉丝 790原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值