Какое исключение я должен выдать?

Ну, несмотря на то, что Вы попросили, чтобы мы не "просто" связались с другими ресурсами, довольно глупо, когда там уже существует выращенное сообщество (и растущий) ресурс, это действительно довольно хорошо: Книга Сообщества Мерзавца. Серьезно, это 20 + вопросы в вопросе будет совсем не кратким и последовательным. Книга Сообщества Мерзавца доступна и как HTML и как PDF и отвечает на многие Ваши вопросы с ясным, хорошо отформатированным, и коллега рассмотрел ответы и в формате, который позволяет Вам переходить прямо к Вашей проблеме под рукой.

увы, если мое сообщение действительно расстраивает Вас тогда, я удалю его. Просто скажите так.

19
задан BartoszKP 15 April 2015 в 12:03
поделиться

5 ответов

Вы должны унаследовать свой собственный класс от std :: exception , так что существует некоторый способ единообразной обработки исключений.

Если это кажется излишним, вы можете бросить std :: logic_error или одного из других стандартных типов исключений, предназначенных для использования приложениями.

Вы также можете использовать их в качестве базовых классов для ваших собственных более конкретных исключений: это сэкономит немного времени, потому что они позаботятся о реализации метода what за вас.

Обратите внимание, что глубокие иерархии исключений могут быть непригодным для использования, потому что вы в основном заранее предполагаете, как классифицировать ошибки, а ваши клиенты могут не согласиться.

19
ответ дан 30 November 2019 в 03:38
поделиться

Вот фрагмент кода, который показывает, как расширить и использовать 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 ()), чтобы указать, что они сами не будут генерировать исключения. Вот где ошибка. Гарантируется ли, что вызов 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,

12
ответ дан 30 November 2019 в 03:38
поделиться

Если вы можете использовать ускорение, вы должны это сделать. Обратитесь к по этой ссылке , чтобы узнать, как использовать исключения повышения. Вы также можете создать свою собственную иерархию классов исключений, как указано в других ответах, но вам нужно позаботиться о тонких аспектах, таких как требования «не вытягивать» из метода «что». Базовая схема того, как это можно сделать в строках 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
    };

  }
1
ответ дан 30 November 2019 в 03:38
поделиться

Обычно вы должны наследовать свои собственные классы исключений из std :: exception и его производных для представления ошибок, относящихся к домену вашего приложения, например, если вы имеете дело с файлами, у вас должно быть FileNotFoundException, которое включает путь к файлу и другую важную информацию, таким образом вы можете создавать блоки перехвата для обработки определенных типов ошибок и исключения других, вам также следует воздерживаться от генерирования или перехвата исключений, не относящихся к классу.

Взгляните на похожие иерархии исключений в . NET и Java, чтобы узнать, как моделировать общие ошибки (ошибки файлов, ошибки ввода-вывода, ошибки сети и т. Д.)

0
ответ дан 30 November 2019 в 03:38
поделиться

Я подумал, что было бы интересно опубликовать реальный код для изменения. Это класс исключения, который использует моя собственная библиотека утилит:

//---------------------------------------------------------------------------
// 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
4
ответ дан 30 November 2019 в 03:38
поделиться
Другие вопросы по тегам:

Похожие вопросы: