在浏览了一些关于异常处理的链接(1,2和3)之后,我知道C ++程序几乎可以抛出任何异常(int
,char*
,string
,exception
类)。我知道std::exception
是程序抛出的标准异常的基类。但是,我正在尝试设计一个try
... catch
块:
try
{
MyFunc();
}
catch (certain exceptions)
{
// deal with the exception accordingly
}
catch (the rest of the exceptions)
{
// deal with these accordingly
}
虽然MyFunc()
包含以下内容:
void MyFunc()
{
...
if (certain condition is true) throw exception;
...
}
麻烦的是,在MyFunc
函数的那一部分中,我不确定应该抛出什么类型的异常。为了通过实现我自己的异常类来保持代码清洁,我不知道什么是实现这样的异常类的好方法。
答案 0 :(得分:19)
您可以从std::exception
派生自己的类,以便有一些统一处理异常的方法。
如果这看起来有点矫枉过正,您可以抛出std::logic_error
或其他一些用于应用程序的标准异常类型。
您也可以将这些作为基类用于您自己的更具体的例外:这样可以节省一些工作,因为它们会为您实施what
方法。
请注意,深层异常层次结构可能无法使用,因为您基本上是在预先猜测如何对错误进行分类,而您的客户可能不同意。
答案 1 :(得分:12)
这是一个代码片段,展示了如何扩展和使用std :: exception类: (顺便说一句,这段代码有一个错误,我稍后会解释)。
#include <iostream>
#include <string>
#include <exception>
class my_exception : public std::exception
{
public:
explicit my_exception(const std::string& msg)
: msg_(msg)
{}
virtual ~my_exception() throw() {}
virtual const char* what() const throw()
{
return msg_.c_str();
}
private:
std::string msg_;
};
void my_func() throw (my_exception&)
{
throw my_exception("aaarrrgggg...");
}
int
main()
{
try
{
my_func();
}
catch (my_exception& ex)
{
std::cout << ex.what() << '\n';
}
return 0;
}
请注意,构造函数是显式的,并且声明了析构函数和what()(使用throw())以指示它们自己不会抛出异常。这就是bug的地方。是否保证对msg_.c_str()的调用不会抛出自己的异常?我们用来初始化msg_的字符串构造函数怎么样?它也可以引发异常。我们如何设计一个对成员对象引发的异常安全的异常类?答案是 - 继承自std :: runtime_error或类似的std :: exception子类。因此,实现my_exception的正确方法是:
class my_exception : public std::runtime_error
{
public:
my_exception(const std::string& msg)
: std::runtime_error(msg)
{ }
};
我们不需要覆盖what(),因为它已经在std :: runtime_error中实现了。正确处理消息缓冲区是由std :: runtime_error完成的,因此我们可以确定my_exception本身不会在运行时抛出一些未知错误。
答案 2 :(得分:4)
我认为发布一些真正的代码可能会很有趣。这是我自己的实用程序库使用的异常类:
//---------------------------------------------------------------------------
// a_except.h
//
// alib exception handling stuff
//
// Copyright (C) 2008 Neil Butterworth
//---------------------------------------------------------------------------
#ifndef INC_A_EXCEPT_H
#define INC_A_EXCEPT_H
#include "a_base.h"
#include <exception>
#include <sstream>
namespace ALib {
//------------------------------------------------------------------------
// The only exception thrown directly by alib
//------------------------------------------------------------------------
class Exception : public std::exception {
public:
Exception( const std::string & msg = "" );
Exception( const std::string & msg, int line,
const std::string & file );
~Exception() throw();
const char *what() const throw();
const std::string & Msg() const;
int Line() const;
const std::string & File() const;
private:
std::string mMsg, mFile;
int mLine;
};
//------------------------------------------------------------------------
// Macro to throw an alib exception with message formatting.
// Remember macro is not in ALib namespace!
//------------------------------------------------------------------------
#define ATHROW( msg ) \
{ \
std::ostringstream os; \
os << msg; \
throw ALib::Exception( os.str(), __LINE__, __FILE__ ); \
} \
} // namespace
#endif
这是.cpp文件:
//---------------------------------------------------------------------------
// a_except.h
//
// alib exception handling stuff
//
// Copyright (C) 2008 Neil Butterworth
//---------------------------------------------------------------------------
#include "a_except.h"
using std::string;
namespace ALib {
//---------------------------------------------------------------------------
// exception with optional message, filename & line number
//------------------------------------------------------------------------
Exception :: Exception( const string & msg )
: mMsg( msg ), mFile( "" ), mLine(0) {
}
Exception :: Exception( const string & msg, int line, const string & file )
: mMsg( msg ), mFile( file ), mLine( line ) {
}
//---------------------------------------------------------------------------
// Do nothing
//---------------------------------------------------------------------------
Exception :: ~Exception() throw() {
}
//------------------------------------------------------------------------
// message as C string via standard what() function
//------------------------------------------------------------------------
const char * Exception :: what() const throw() {
return mMsg.c_str();
}
//------------------------------------------------------------------------
// as above, but as C++ string
//------------------------------------------------------------------------
const string & Exception :: Msg() const {
return mMsg;
}
//---------------------------------------------------------------------------
// File name & line number
//---------------------------------------------------------------------------
int Exception :: Line() const {
return mLine;
}
const string & Exception :: File() const {
return mFile;
}
} // namespace
// end
答案 3 :(得分:1)
如果你可以使用提升,那么你应该这样做。有关如何使用提升异常的信息,请参阅this link。您也可以设计自己的异常类层次结构,如其他答案所述,但您需要处理“whathrow”方法中的“nothrow”要求等细微方面。关于如何在boost :: exception行上完成此操作的基本设计解释如下: -
#include <string>
#include <memory>
#include <stdexcept>
/************************************************************************/
/* The exception hierarchy is devised into 2 basic layers.
System exceptions and Logic exceptions. But Logic exceptions are
convertible to the ultimate base 'System' in the system layer.
*************************************************************************/
// the system exception layer
namespace ExH
{
namespace System {
// This is the only way to make predefined exceptions like
// std::bad_alloc, etc to appear in the right place of the hierarchy.
typedef std::exception Exception;
// we extend the base exception class for polymorphic throw
class BaseException : public Exception {
public:
BaseException() throw() {}
explicit BaseException(char const* /*desc*/) throw()
: Exception()
{}
BaseException(BaseException const& that)
: Exception(that)
{}
virtual void raise() const { throw *this; } // used to throw polymorphically
virtual ~BaseException() throw () {}
};
// module level classes compose and catch the descriptive
// versions of layer-exceptions
class DescriptiveException : public BaseException {
public:
explicit DescriptiveException (char const* description) throw()
: description_(description)
{ }
explicit DescriptiveException (std::string const& description) throw()
: description_(description.c_str())
{ }
virtual ~DescriptiveException () throw () {}
DescriptiveException (DescriptiveException const& src) throw()
: BaseException(src)
{
this->description_ = src.description_;
}
DescriptiveException& operator= (DescriptiveException const& src) throw()
{
if (this != &src)
{
this->description_ = src.description_;
}
return *this;
}
/*virtual*/ char const* what () const throw() { return description_; }
/*virtual*/ void raise() const // used to throw polymorphically
{ throw *this; }
protected:
DescriptiveException () throw ();
private:
char const* description_;
};
}
}
// the logic exception layer
namespace ExH
{
namespace Logic
{
// Logic::Exception inherits from System::Exception for the
// following reason. Semantically for some part of the
// system particular instance of Logic::Exception may seem as
// opaque System::Exception and the only way to handle it would
// be to propagate it further. In other words Logic::Exception
// can be seamlessly "converted" to System::Exception if there is
// no part of the system interested in handling it.
//
class BaseException : public System::BaseException
{
public:
BaseException() throw() {}
explicit BaseException(char const* desc) throw()
: System::BaseException(desc)
{}
BaseException(BaseException const& that)
: System::BaseException(that)
{}
virtual void raise() const { throw *this; } // used to throw polymorphically
virtual ~BaseException() throw () {}
};
// module level classes compose and catch the descriptive
// versions of layer-exceptions
class DescriptiveException : public BaseException {
public:
explicit
DescriptiveException (char const* description) throw()
: description_(new std::string(description))
{ }
explicit
DescriptiveException (std::string const& description) throw()
: description_(new std::string(description))
{ }
DescriptiveException(DescriptiveException const& src) throw()
: BaseException(src)
{
// copy the string
std::string* str = new std::string(src.description_.get()->c_str());
description_.reset(str);
}
virtual ~DescriptiveException () throw () {}
/*virtual*/ char const* what () const throw() { return description_->c_str(); }
/*virtual*/ void raise() const { throw *this; }
private:
DescriptiveException& operator= (DescriptiveException const& src) throw(); // copy disabled
std::auto_ptr<std::string> description_; // do not use std::string, as it can throw
};
}
}
/************************************************************************/
/* Users of the exception hierarchy compose specific exceptions as and
when needed. But they can always be caught at the System::Exception base
class level. Some of the standard conversion examples are demonstrated :-
class MyClass {
public:
class Exception_ {};
typedef
Compound <Exception_, Logic::DescriptiveException>
Exception;
class InvalidArgument_ {};
typedef
Compound <InvalidArgument_, Exception>
InvalidArgument;
class NotInitialized_ {};
typedef
Compound <NotInitialized_, Exception>
NotInitialized;
public:
void myFunction1() const throw(NotInitialized);
void myFunctionN() const throw(NotInitialized);
};
void MyClass::myFunction1() const {
throw NotInitialized("Not Inited!");
}
void MyClass::myFunctionN() const {
try {
// call myFunction1()
}
catch(NotInitialized const& e){
// use e
}
}
This has to be per-class basis. The exposed module will have an exception
specification which will catch all the sub-class exceptions. The calling
module will in turn rely on this exception-specification. This will allow
us to have generalized exception-catching at the application-level and
more specialized exception-catching at the specific module level. */
/************************************************************************/
// a simple template to compose the exceptions as per conversion requirements
namespace ExH
{
template <typename Type, typename Base>
class Compound : public Base
{
public:
explicit Compound (char const* description) throw ()
: Base(description)
{}
explicit Compound (std::string const& description) throw ()
: Base(description)
{}
Compound (Compound const& src) throw ()
: Base(src)
{}
virtual ~Compound () throw () {}
protected:
Compound () throw () {}
private:
Compound& operator= (Compound const& src) throw (); // disable copy
};
}
答案 4 :(得分:0)
通常你应该从std :: exception及其派生类派生你自己的异常类来表示与你的应用程序域相关的错误,例如,如果你处理文件你应该有FileNotFoundException包含文件路径和其他相关信息,这样你可以创建catch块来处理某些错误类型而忽略其他错误类型,你也应该避免抛出或捕获非类异常。
查看.NET和Java中的类似异常层次结构,了解如何建模一般错误(文件错误,IO错误,网络错误等)