源码 头文件  sdf_exception.h

#pragma once#include <exception>
#include <string>namespace sdf {namespace common{using sdf_error_code_t = uint32_t;class SdfException : std::exception{public:explicit SdfException(sdf_error_code_t errorCode) : error_code(error_code){};SdfException(sdf_error_code_t errorCode,std::string error_message){}SdfException(sdf_error_code_t x,sdf_error_code_t y,sdf_error_code_t z):error_code(pack211(x,y,z)){}SdfException(sdf_error_code_t x,sdf_error_code_t y,sdf_error_code_t z,std::string error_message){}const char *what() const noexcept override;sdf_error_code_t get_error_code() const{return error_code;}public:static sdf_error_code_t pack211(sdf_error_code_t x,sdf_error_code_t y,sdf_error_code_t z){return x << 16U | y << 8U | z;           //Appending u to any integral constant makes the compiler interpret it as unsigned.}private:sdf_error_code_t error_code;std::string error_message;bool error_message_packed = false;//< flag for lazy packing error message};}
}

学习

  • SdfException(sdf_error_code_t error_code) : error_code(error_code) {}这个是 C++ 类构造函数初始化列表 参考
  • const char * 、char const *、 char * const 三者的区别  参考链接  参考链接
  • const char *what() const      参考链接
  • noexcept override;   参考链接  参考链接 参考链接 参考链接

源文件  sdf_exception.cpp

#include "sdf_exception.h"#include "logging.h"namespace sdf {
namespace common {std::string pack_error_message(sdf_error_code_t error_code,const std::string &error_message) {char buffer[1024];auto length =std::snprintf(buffer, sizeof(buffer), "sdf exception: [0x%08x] %s\n",error_code, error_message.c_str());if (length < 0 || length >= static_cast<int>(sizeof(buffer))) {log_fatal("Unexpected error message length: %s", length);}return buffer;
}SdfException::SdfException(sdf_error_code_t error_code,std::string error_message): error_code(error_code), error_message(std::move(error_message)) {}SdfException::SdfException(sdf_error_code_t x, sdf_error_code_t y,sdf_error_code_t z, std::string error_message): error_code(pack211(x, y, z)), error_message(std::move(error_message)) {}const char *SdfException::what() const noexcept {if (!error_message_packed) {const_cast<bool &>(error_message_packed) = true;const_cast<std::string &>(error_message) =pack_error_message(error_code, error_message);}return error_message.c_str();
}} // namespace common
} // namespace sdf

学习

  • snprintf() 参考链接
  • 浅析c++中的类型转换--static_cast  参考链接
  • std::move 参考链接

代码调用

代码层次结构

所需要的配套文件

logging.h

#pragma oncenamespace sdf {namespace common {enum LogLevel {SDF_LOG_DEBUG,SDF_LOG_INFO,SDF_LOG_WARN,SDF_LOG_ERROR,SDF_LOG_FATAL,SDF_LOG_IMPORTANT_INFO};void set_logging_level(LogLevel level);#define LOGGER_DECLARATION(level) void log_##level(const char *format, ...);LOGGER_DECLARATION(debug)LOGGER_DECLARATION(info)LOGGER_DECLARATION(warn)LOGGER_DECLARATION(error)LOGGER_DECLARATION(fatal)LOGGER_DECLARATION(important)#undef LOGGER_DECLARATION} // namespace common
} // namespace sdf

logging.cpp

#include "logging.h"
//#include "sdf_config.h"#include <cstdarg>
#include <cstdio>
#include <ctime>
#include <mutex>#ifdef ENABLE_SYSLOG
#include <syslog.h>
#endifnamespace sdf {namespace common {const char *get_current_time() {static char buffer[80];time_t raw_time;std::time(&raw_time);std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S",localtime(&raw_time));return buffer;}class Logger {public:static inline void set_logging_level(LogLevel level) {default_logging_level = level;}#ifndef ENABLE_SYSLOGstatic void vlog(LogLevel level, const char *format, va_list ap) {if (level < Logger::default_logging_level) {return;}auto endpoint = stdout;if (level == SDF_LOG_ERROR || level == SDF_LOG_FATAL) {endpoint = stderr;}const char *level_info = nullptr;switch (level) {case SDF_LOG_DEBUG:level_info = "DEBUG";break;case SDF_LOG_INFO:case SDF_LOG_IMPORTANT_INFO:level_info = "INFO";break;case SDF_LOG_WARN:level_info = "WARN";break;case SDF_LOG_ERROR:level_info = "ERROR";break;case SDF_LOG_FATAL:level_info = "FATAL";break;default:break;}std::lock_guard<std::mutex> lock(log_mutex);::fprintf(endpoint, "[%s][%s] ", get_current_time(), level_info);::vfprintf(endpoint, format, ap);::fprintf(endpoint, "\n");if (level == SDF_LOG_FATAL) {::abort();}}#elsestatic void vlog(LogLevel level, const char *format, va_list ap) {if (level < Logger::default_logging_level) {return;}int syslog_level = 0;switch (level) {case SDF_LOG_DEBUG:syslog_level = LOG_DEBUG;break;case SDF_LOG_INFO:syslog_level = LOG_INFO;break;case SDF_LOG_IMPORTANT_INFO:syslog_level = LOG_NOTICE;break;case SDF_LOG_WARN:syslog_level = LOG_WARNING;break;case SDF_LOG_ERROR:syslog_level = LOG_ERR;break;case SDF_LOG_FATAL:syslog_level = LOG_CRIT;break;default:break;}// std::lock_guard<std::mutex> lock(log_mutex);vsyslog(syslog_level, format, ap);if (level == SDF_LOG_FATAL) {::abort();}}#endifstatic inline void log(LogLevel level, const char *format, ...) {va_list ap;va_start(ap, format);vlog(level, format, ap);va_end(ap);}private:static LogLevel default_logging_level;static std::mutex log_mutex;};LogLevel Logger::default_logging_level = LogLevel::SDF_LOG_INFO;std::mutex Logger::log_mutex;void set_logging_level(LogLevel level) { Logger::set_logging_level(level); }#define LOGGER_DEFINITION(level, level_tag)                                    \void log_##level(const char *format, ...) {                                  \va_list ap;                                                                \va_start(ap, format);                                                      \Logger::vlog(level_tag, format, ap);                                       \va_end(ap);                                                                \}LOGGER_DEFINITION(debug, SDF_LOG_DEBUG)LOGGER_DEFINITION(info, SDF_LOG_INFO)LOGGER_DEFINITION(warn, SDF_LOG_WARN)LOGGER_DEFINITION(error, SDF_LOG_ERROR)LOGGER_DEFINITION(fatal, SDF_LOG_FATAL)LOGGER_DEFINITION(important, SDF_LOG_IMPORTANT_INFO)#undef LOGGER_DEFINITION} // namespace common
} // namespace sdf

random_generator.cpp

#include "random_generator.h"#include "../common/sdf_exception.h"#include <string>
#include <iostream>std::string::size_type sdf::sys::GenerateRandom::NDSKeyStore_Common_GenerateRandom( size_t uiLength){std::cout << uiLength << std::endl;try {if(uiLength != 1024)
//            throw common::SdfException(-1);throw common::SdfException(45,"There is an error in the program, please solve it immediately!!");
//            throw common::SdfException(1,2,3);
//            throw common::SdfException(1,2,3,"There is an error in the program, please solve it immediately!");} catch (common::SdfException& e) {//        std::cerr<<"ERROR CODE:"<< e.get_error_code() << std::endl;std::cerr << e.what() << std::endl;}}

random_generator.h

#pragma once#include <cstddef>
#include <string>namespace sdf {namespace sys{class GenerateRandom {public:explicit GenerateRandom() = default;virtual ~GenerateRandom() = default;static std::string::size_type NDSKeyStore_Common_GenerateRandom(size_t uiLength);};}// namespace sys
}// namespace sdf

main函数调用

#include <iostream>
#include <sstream>#include "../src/algorithm/random/random_generator.h"
#include "../src/algorithm/common/StringBuffer.h"#define BUF_SIZE 1024
int main(){sdf::sys::GenerateRandom::NDSKeyStore_Common_GenerateRandom(1026);return 0;}

注意事项:

  • catch不一定需要紧紧跟着try

针对C++异常的学习相关推荐

  1. java 异常_Java学习——异常与异常处理

    学习这件事不在乎有没有人教你,最重要的是在于你自己有没有觉悟和恒心.--法布尔 一.异常简介 异常:程序出现意外导致中断指令流的一种事件. 异常是一个类,继承于Throwable类,其中包括2个主要大 ...

  2. 深鉴科技联合创始人汪玉:针对机器视觉的深度学习处理器(附视频、PPT下载)...

    本内容选自清华大学电子系副教授.深鉴科技联合创始人汪玉于2018年4月27日在清华大学主楼接待厅数据科学研究院举办的第二届"大数据在清华"高峰论坛所做题为<针对机器视觉的深度 ...

  3. ARM学习(3) 异常模式学习(CortexR5)

    笔者简单介绍一下ARM CortexR5异常模式 学习 1.由来 笔者工作中用到了SSD的主控芯片是基于CortexR5系列的,所以研究一下CortexR5系列的一些异常模型. 什么时候会用到这些异常 ...

  4. PHP - 异常/错误 - 学习/实践

    1.应用场景 主要用于了解熟悉并正确使用PHP异常处理机制. 2.学习/操作 1. 文档阅读 PHP Exception - php完全自学手册 - php中文网手册 深入探讨 PHP 错误异常处理机 ...

  5. JAVA捕捉输入格式异常_Java学习(四).异常处理

    异常处理 任何一个软件或程序都可能在运行的过程中出现故障,问题的关键是故障出现以后如何处理?谁来处理?怎样处理?处理后系统能否恢复正常的运行?本章在介绍Java处理这类问题基本方法的基础上,讨论包含异 ...

  6. .NET Core开发实战(第22课:异常处理中间件:区分真异常与逻辑异常)--学习笔记(下)...

    接下来介绍使用代理方法的方式,也就是说把 ErrorController 整段逻辑直接定义在注册的地方,使用一个匿名委托来处理,这里的逻辑与之前的逻辑是相同的 app.UseExceptionHand ...

  7. .NET Core开发实战(第22课:异常处理中间件:区分真异常与逻辑异常)--学习笔记(上)...

    22 | 异常处理中间件:区分真异常与逻辑异常 这一节我们来讲解一下错误处理的最佳实践 系统里面异常处理,ASP.NET Core 提供了四种方式 1.异常处理页 2.异常处理匿名委托方法 3.IEx ...

  8. Java基础学习总结(76)——Java异常深入学习研究

        异常机制是指当程序出现错误后,程序如何处理.具体来说,异常机制提供了程序退出的安全通道.当出现错误后,程序执行的流程发生改变,程序的控制权转移到异常处理器. 异常处理的流程     当程序中抛 ...

  9. java 异常_学习Java,你需要知道这些Java异常

    文章目录 异常处理的概念 异常的基本概念 Java异常处理机制的优点 错误的分类 异常的分类 预定义的一些常见异常 异常的处理 抛出异常 捕获异常的语法 生成异常对象 声明自己的异常类 异常处理的概念 ...

最新文章

  1. Linux-常用系统管理命令
  2. 【机器学习基础】机器学习模型的度量选择(下)
  3. 解决linux不能安装g++问题
  4. wordcloud python3.7_[原创]win7/64位系统+python3.7.2下安装wordcloud库失败之解决——一个莫名其妙的方法...
  5. NUXT内存泄漏引发问题
  6. TIOBE 7月编程语言排行:各大城市程序员的工资状况又又又涨了
  7. 设置电脑开机自启动软件,exe/jar均可
  8. Linux内核启动中驱动初始化过程
  9. stata中安装meta分析模块
  10. 计算机中级应用,计算机办公软件应用: 中级
  11. 小猿圈:web前端工程师工资有多高?
  12. 绿色下载:CYY屏幕截图助手1.3
  13. Eclipse Embedded CDT
  14. spring boot rest例子
  15. 聚醋酸乙烯酯(PVAc)乳剂市场现状及未来发展趋势
  16. 与苹果一起下坠|深氪Lite
  17. web前端学习(CSS篇)
  18. 例说图解TCP/IP协议族--TLS篇(1)抓包分析SSL/TLS握手
  19. ENC28J60学习笔记——第4部分
  20. 安全集成SAP与微信钉钉

热门文章

  1. linux怎么设置tomcat自动启动,linux添加tomcat服务并设置开机启动
  2. python读取单波段影像dem
  3. [你必须知道的.NET] 第六回:深入浅出关键字---base和this
  4. Windows高级编程学习笔记(一)
  5. Python 数据分析三剑客之 Matplotlib(七):饼状图的绘制
  6. 【qduoj - 夏季学期创新题】最长公共子串(水题暴力枚举,不是LCS啊)
  7. 【POJ - 1789】【ZOJ - 2158】【SCU - 1832】Truck History (最小生成树)
  8. android 添加so,Android studio 中添加 .so 文件
  9. 华为虚拟服务器lanip地址,2018软考网络工程师《华为基础实验》十九配置路由器为DHCPServer...
  10. linux依赖包在哪个目录,命令-Linux cmd在jar中搜索类文件,而与jar路径无关