c++中所有内容的基类
Base class of everything in c++
在Java中,Object
类是所有类的基类。C++中也有这样的类吗?
我提出这个问题的动机是:
try
{
if (something) throw int(a);
if (something) throw char(b);
if (something) throw float(c);
}
catch(...)
{
handle
}
除此之外,还有其他方法可以使用单个catch块来处理所有这些异常吗?
C++中没有通用基类。
异常类通常应该从std::exception
派生,以便可以使用catch(const std::exception&)
。
catch(...)
捕获任何异常对象类型(包括基元类型)。可以使用throw;
:在catch
块内重新抛出
try
{
if (something) throw int(a);
if (something) throw char(b);
if (something) throw float(c);
}
catch(...)
{
if(stillFailed) throw; // throws the same exception again
}
也可以使用std::current_exception()
在catch(...)
块内获取表示抛出对象(未知类型)的std::exception_ptr
对象。然后可以将它与其他std::exception_ptr
对象进行相等性比较,或者使用std::rethrow_exception()
从另一个函数中重新派生。看见http://en.cppreference.com/w/cpp/header/exception。无法直接访问异常对象,因为其类型未知。
std::string
(毕竟,即使是最复杂的程序也只是字符数组)。
将对象编码为文本形式,并在处理端解析/解释它。
template<class T>
std::string toString(const T& x);
try
{
if (something) throw toString(int(a));
if (something) throw toString(char(b));
if (something) throw toString(float(c));
}
catch(const std::string& ex)
{
decode and handle
}
然而,如果你愿意采用这种方法,那么C++不是进行编程的合适语言——最好改用面向文本或动态语言。
不,有任何其他方法可以单独使用单个catch块来处理所有这些异常。
需要不同的catch块来处理不同的数据类型throw。喜欢对于int捕获(int m)
对于char(字符m)
等等。
相关文章:
- std::具有相同基类的类的变体
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 基类中的函数名称解析
- C++初始化基类
- 如何通过派生类函数更改基类中的向量
- 如何定义一个纯抽象基类
- 如何使用基类指针引用派生类成员
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 为什么此派生对象无法访问基类的后递减方法?
- 公开最直接的基类模板名称
- 当基类是依赖类型时,这是一个缺陷吗
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- 模板基类中的静态变量
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 继承和友元函数,从基类访问受保护的成员