c++ std::logic_error 异常的使用方法

*** 简单的用法就是如下所示. 抛出一个logic_error()异常,接住,展示.
$ cat main.cpp
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
    try
    {
//        logic_error e("test this");
        logic_error e(string("test this ")+"and that"); //显示了字符串类可以直接用+来连接
        throw e; //exception 用法, 如此构造和抛出异常
    }
    catch(exception &ex)    // exception 的用法,如此接受异常
    {
        printf("catch %s\n",ex.what()); //exception 用法,如此访问异常
    }
    return 0;
}

不爽的地方是ctags认不准这种结构了, 在vim中查看很不方便.
在gdb 中也不让查看. 非常不爽!
(gdb) p e
  $1 = <incomplete type>
(gdb) ptype e
  type = class std::logic_error {
      <incomplete type>
  }
 
*** 那这个logic_error 到底是啥呢?
 有时候,c++ 的封装确实不好说是好是坏!
logic_error 是一个exception 的继承类,
在/usr/include/c++/9/stdexcept 文件中定义.
通过qtcreator 找到, 有时IDE 确实在找定义方面更准更强!
// 下面内容有简化
 class logic_error : public exception
  {
    char * _M_msg; //保存信息

public:
    logic_error(const string& __arg) _GLIBCXX_TXN_SAFE;
    logic_error(const char*) _GLIBCXX_TXN_SAFE;
    logic_error(logic_error&&) noexcept;
    logic_error& operator=(logic_error&&) noexcept;
    logic_error(const logic_error&) = default;
    logic_error& operator=(const logic_error&) = default;
    virtual ~logic_error() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW;

/** Returns a C-style character string describing the general cause of
     *  the current error (the same string passed to the ctor).  */
    virtual const char*
    what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW;
  };

可以看出它主要是一些构造函数 和 what() 函数, 无它了, 再看一下exception 类

class exception
  {
  public:
    exception() _GLIBCXX_NOTHROW { }
    virtual ~exception() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW;
    exception(const exception&) = default;
    exception& operator=(const exception&) = default;
    exception(exception&&) = default;
    exception& operator=(exception&&) = default;

/** Returns a C-style character string describing the general cause
     *  of the current error.  */
    virtual const char*
    what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW;
  };

  看来exception 就是一个接口类,logic_error是其一个实现类了.
  会像示例那样使用就可以了.

再给一个具体的使用实例,加深对std::exception ,std::logic_error使用的理解。

#include <iostream> // std::cout std::endl
#include <exception> // std::domain_error, logic_error
#include <cmath> // std::sqrtdouble mysqrt(double value)
{if (value < 0){//        throw std::exception("需要开平方的参数不能是负数");  // exception 不支持字符串参数throw std::logic_error("需要开平方的参数不能是负数");
//      throw std::domain_error("需要开平方的参数不能是负数"); // 也可以用domain_error,与logic_error 是2种实现,你也可以书写自己的exception 类,继承自std::exception}return sqrt(value);
}int main(void)
{try{std::cout << mysqrt(100) << std::endl;std::cout << mysqrt(-100) << std::endl;return 0;}catch (const std::exception &e){std::cout << e.what() << std::endl;}return 0;
}

如果对std::logic_error 还有疑惑的地方,我这里实现一个自己的exception, 它的功能等同于std::logic_error, 并且还给出了测试程序,一并在代码段中给出.

$ cat myexception.h
#ifndef _MY_EXCEPTION_H
#define _MY_EXCEPTION_H
#include <string>
#include <exception>
class MyException : public std::exception
{ //定义MyException 类public:MyException(const std::string &msg): _msg(msg){}~MyException() throw() {}const char *what() const throw() { return _msg.c_str(); }private:std::string _msg;
};
#endifhjj@hjj-7090:~/test/myexception$ cat main.cpp
#include <iostream>
#include "myexception.h"
using namespace std;
int main(void)
{try{throw MyException("an error ocurred!");printf("this line won't executed!\n");}catch(exception &e){cout<<"catched "<<e.what()<<endl;}
}

执行结果:

$ ./myexception
catched an error ocurred!

c++ std::exception,std::logic_error 异常的使用方法相关推荐

  1. C++/C++11中std::exception的使用

    std::exception:标准异常类的基类,其类的声明在头文件<exception>中.所有标准库的异常类均继承于此类,因此通过引用类型可以捕获所有标准异常. std::excepti ...

  2. std::exception的使用

    std::exception:标准异常类的基类,其类的声明在头文件<exception>中.所有标准库的异常类均继承于此类,因此通过引用类型可以捕获所有标准异常. std::excepti ...

  3. C++11 并发指南四(future 详解三 std::future std::shared_future)

    上一讲<C++11 并发指南四(<future> 详解二 std::packaged_task 介绍)>主要介绍了 <future> 头文件中的 std::pack ...

  4. C++ 并发指南< future >(3)std::future std::shared_future

    std::future介绍 简单地说,std::future 可以用来获取异步任务的结果,因此可以把它当成一种简单的线程间同步的手段. std::future 通常由某个 Provider 创建,你可 ...

  5. C/C++ 异常( std::exception)

    C++提供异常主要是为了分割库异常与调用者之间的分割 平常当我们开发一个lib库时,一般lib库里的函数发生异常都会通过返回值来告诉用户,但是这样的开发属实有点过于麻烦了 如: int test(){ ...

  6. terminating with uncaught exception of type std::bad_cast: std::bad_cast

    terminating with uncaught exception of type std::bad_cast: std::bad_cast 我这里的情况: 我有两个so A 和B,调用程序c 把 ...

  7. Mongodb std::exception::what(): basic_filebuf::underflow error reading the file: iostream error

    报错信息 2021-08-30T21:37:47.238+0800 F - [main] terminate() called. An exception is active; attempting ...

  8. c++:警告:warning: catching polymorphic type ‘class std::exception’ by value

    文章目录 警告 gcc 选项 原因 警告 exception.cpp: In function 'int main()': exception.cpp:14:17: warning: catching ...

  9. Unhandled exception at 0x00007FFE7BFD8A5C in wb.exe: Microsoft C++ exception: std::out_of_range at m

    在执行C++ imshow代码是出现 如下错误: 第一次类似报错 : 另一个报错博文中 中 执行imshow函数时的报错 第二次该类报错: [cpp] view plaincopy print? ve ...

最新文章

  1. JGG:COVID-19感染导致儿童上呼吸道和肠道菌群持续失衡
  2. ansible模块command、shell、raw、script
  3. mysql全量备份与增量备份_Mysql增量备份与全量备份
  4. 详解JSONObject.parseObject和JSONObject.fromObject——Web网络系列学习笔记
  5. linux 命令分号,linux命令之间的分号,, ||
  6. mysql error1045 yes_MYSQL ERROR 1045 (28000): Access denied for user (using password: YES)问题的解决...
  7. 三、 安装项目依赖以及启动项目
  8. 逻辑程序设计语言Prolog
  9. html5拼音显示,HTML5:给汉字加拼音?收起展开组件?
  10. 妈耶,摆脱机器音,二次宅的歌姬女友彻底活了
  11. html制作备案表格代码,如何在首页中插入备案编号HTML代码
  12. 各大编辑器的常用快捷键
  13. xamp环境搭建Pikachu实验环境搭建
  14. ParaView绘制自由水面的等值线图
  15. PTA L1-016 查验身份证(15分)
  16. 02-2017.07-计算机设计大赛《盲人的眼睛》
  17. P1217 [USACO1.5]回文质数 Prime Palindromes(打表)
  18. 人工智能相关论文 2022 accepted papers list
  19. Linux C++ IDEs
  20. 知乎上线诺贝尔奖主题圆桌 让科普更加多元有趣

热门文章

  1. java实现随机数生成算法_Java 语言实现的随机数生成算法
  2. HDU 4394 BFS
  3. 【分布式微服务】消息中心初步搭建
  4. mySQL 1142 错误码
  5. oracle设置字符集为gbk,rac 环境下修改oracle数据库字符集为GBK
  6. 5000字加21图文 | 抓包带你体验同网段的通信过程,这些细节很关键
  7. 从网瘾少年逆袭拿到微软、字节等offer(上)
  8. AutoCAD Electrical(ACE)的基本操作——画布与新建圆、直线
  9. 判断一个数是不是质数
  10. 结对编程java实现四则运算(张铭 吴昊)