2014-12-03 62 views
0

今天我一直在处理异常处理。如果它在void函数中,我已经想通过它来工作,但是如何处理必须返回值的函数。主要的最后3行是“问题”发生的地方。我之前发现这个链接可以帮助我解决这个问题,但是我的异常处理必须全部包含在类结构中,所以我不能在main中尝试/ throw/catch。我想了解发生了什么事。 [1]:What type of exception should I throw?C++类包含异常处理

在此先感谢。

#include <iostream> 
#include <exception> 

class out_of_range : public std::exception 
{ 
private: 
    std::string msg; 

public: 
    out_of_range(const std::string msg) : msg(msg){}; 
    ~out_of_range(){}; 

    virtual const char * what() 
    { 
     return msg.c_str(); 
    } 
}; 
class divide 
{ 
private: 
    int a; 
    int * _ptr; 
public: 
    divide(int r): a(r), _ptr(new int[a]) {}; 
    ~divide(){ delete[] _ptr; }; 

    int get(int index) const 
    { 
     try 
     {  
      if (index < 0 || index >= a) 
       throw out_of_range("Err");    
      else 
       return _ptr[index]; 
     } 
     catch (out_of_range & msg) 
     { 
      std::cout << msg.what() << std::endl; 
     } 
    } 
    int &get(int index) 
    { 
     try 
     { 
      if (index < 0 || index >= a) 
       throw out_of_range("Err"); 
      else 
       return _ptr[index]; 
     } 
     catch (out_of_range & msg) 
     { 
      std::cout << msg.what() << std::endl; 
     } 
    } 
}; 

int main() 
{ 
    divide test(6); 
    for (int i(0); i < 6; ++i) 
    { 
     test.get(i) = i * 3; 
     std::cout << test.get(i) << std::endl; 
    } 
    std::cout << "test.get(10): " << test.get(10) << std::endl; 
    test.get(3) = test.get(10); 
    std::cout << "test.get(3): " << test.get(3) << std::endl; 

    return 0; 
} 

回答

2

如果赶上在divide::get方法例外,它必须以某种方式告诉调用者出现了错误。因此实现可能看起来类似的东西:

class divide 
{ 
//.. 
    bool get(int nIndex, int* nResult); 
//... 
int main() 
//... 
    int nRes = 0; 
    if(!test.get(10, &nRes)) 
     cout << "Something is not right"; 

如果有很多事情可以去不对劲,你可以返回bool一些错误代码代替。但是如果你使用这个方法,你的异常类就不需要了,你可以直接返回错误而不会引发异常。