码迷,mamicode.com
首页 > 编程语言 > 详细

C++异常类的定义和使用以及我对异常类的理解

时间:2014-11-24 00:54:24      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   使用   sp   for   

  异常类的作用就是在执行我们自己的某个功能函数出现意外情况时,为了方便查找错误出处,可以在意外发生时抛出异常
(1).首先定义自己的异常类 可以直接定义也可以从标准异常类派生
    class  CEGUIEXPORT Exception
    {
    public:
        virtual ~Exception(void);
        const String& getMessage(void) const  {return d_message;}
        const String& getName() const { return d_name; }
        const String& getFileName(void) const  {return d_filename;}
        const int getLine(void) const  {return d_line;}
    protected:
        Exception(const String& message = "", const String& name ="CEGUI::Exception", const String& filename = "", int line = 0);
        String d_message;
        String d_filename;
        String d_name;
        int d_line;
    };

    //------------------------------------------------------------------------
    Exception::Exception(const String& message, const String& name, const String& filename, int line)
        : d_filename(filename), d_line(line), d_message(message), d_name(name)
    {
        // Log exception or send it to error stream (if logger not available)
        Logger* logger = Logger::getSingletonPtr();
        if (logger)
        {
            logger->logEvent(name + " in file " + filename  + "(" + PropertyHelper::intToString(line) + ") : " + message, Errors);
        }
        else
        {
            std::cerr << name << " in file " << filename.c_str() << "(" << line << ") : " << message.c_str() << std::endl;
        }
    }
    //------------------------------------------------------------------------
    Exception::~Exception(void)
    {
    }
(2).派生出具体的异常类 此处就是不便归类的异常
    class CEGUIEXPORT UnknownObjectException : public Exception
    {
    public:
        UnknownObjectException(const String& message, const String& file = "unknown", int line = 0)
            : Exception(message, "CEGUI::UnknownObjectException", file, line) {}
    };
   #define UnknownObjectException(message)  \
        UnknownObjectException(message, __FILE__, __LINE__)

(3).在具体的功能函数里,在可能出现异常的地方设置抛出异常
const Image& Imageset::getImage(const String& name) const
{
   ImageRegistry::const_iterator pos = d_images.find(name);

   if (pos == d_images.end())   //这里可能会因为找不到图形文件造成意外 为了处理这种意外可以在此处抛出异常
   {
    throw UnknownObjectException("The Image named ‘" + name + "‘ could not be found in Imageset ‘" + d_name + "‘.");   //抛出异常时会创建一个异常类对象,就会执行异常类的构造函数,从而执行到我们赋予异常类的一些特殊行为,比如向日志里输出错误信息等
   }
   return pos->second;
}
(4).使用可能出现异常的功能函数时,使用try{} catch(){}块来截获异常并进行处理
 try

{
    image = &ImagesetManager::getSingleton().getImageset(imageSet)->getImage(imageName);
}
catch (UnknownObjectException&)
{
    image = 0;
}

 

 

下面是一个Win32控制台下的ExceptionDemo

 1 // ExceptionDemo.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include<afx.h>
 6 #include <string>
 7 #include <afxwin.h>
 8 
 9 using namespace std;
10 
11 
12 class Exception
13 {
14 public:
15     virtual ~Exception(void) {}
16     const string&    getMessage(void)    const        {return d_message;}
17     const string&    getName()            const        {return d_name; }
18     const string&    getFileName(void)    const        {return d_filename;}
19     const int        getLine(void)        const        {return d_line;}
20 protected:
21     Exception(const string& message = "", const string& name ="ExceptionDemo::Exception", 
22         const string& filename = "", int line = 0) : d_filename(filename), d_line(line),d_message(message), d_name(name)
23     {
24         CString str;
25         str.Format("name: %s in file: %s ( %d ): %s",name.c_str(),filename.c_str(),line,message.c_str());
26         AfxMessageBox(str);
27     }
28     string    d_message;
29     string d_filename;
30     string d_name;
31     int d_line;
32 };
33 
34 class UnknownObjectException : public Exception
35 {
36 public:
37     UnknownObjectException(const string& message, const string& file = "unknown", int line = 0)
38         : Exception(message, "ExceptionDemo::UnknownObjectException", file, line) 
39     {
40 
41     }
42 };
43 
44 #define UnknownObjectException(message)  45     UnknownObjectException(message, __FILE__, __LINE__)
46 
47 
48 void function(int n)
49 {
50     if (n>5)
51         throw UnknownObjectException("pass the n volue limited!");
52 }
53 
54 int _tmain(int argc, _TCHAR* argv[])
55 {
56     try
57     {
58         function(6);
59     }
60     catch (UnknownObjectException& e)
61     {
62         AfxMessageBox("抓到了异常!");
63     }
64     return 0;
65 }

 


 

C++异常类的定义和使用以及我对异常类的理解

标签:style   blog   io   ar   color   os   使用   sp   for   

原文地址:http://www.cnblogs.com/rushmaster/p/4117795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!