2012-07-24 108 views
4

,我有以下我的構造函數的代碼塊(這只是一個例子,這個問題是不是split,而約拋出一般異常。此外,升壓庫不能使用。拋出異常的通用理由C++

Transfer::Transfer(const string &dest){ 
    try{ 
    struct stat st; 
    char * token; 
    std::string path(PATH_SEPARATOR) // if it is \ or/this macro will solve it 
    token = strtok((char*)dest.c_str(), PATH_SEPARATOR) // 
    while(token != NULL){ 
     path += token; 
     if(stat(path.c_str(), &st) != 0){ 
      if(mkdir(path.c_str()) != 0){ 
       std:string msg("Error creating the directory\n"); 
       throw exception // here is where this question lies 
      } 
     } 

     token = strtok(NULL, PATH_SEPARATOR); 
     path += PATH_SEPARATOR; 

    } 
    }catch(std::exception &e){ 
     //catch an exception which kills the program 
     // the program shall not continue working. 
    } 

} 

我想是拋出一個異常如果目錄不存在,它不能被創建。我想拋出一個通用的異常,我怎麼能做到這一點在C++? PS:dest has th Ë格式如下:

dest = /usr/var/temp/current/tree 
+3

'令牌= strtok的((字符*)DEST做到這一點.c_str(),PATH_SEPARATOR)//'ouch – chris 2012-07-24 16:30:01

+0

@chris你有更好的建議嗎? – cybertextron 2012-07-24 16:31:17

+0

Boost文件系統有一個'create_directories',它爲你免費提供所有這些,並且具有很好的錯誤語義。 – Flexo 2012-07-24 16:33:17

回答

7

請檢查this answer。這就解釋瞭如何使用自己的異常類

class myException: public std::runtime_error 
{ 
    public: 
     myException(std::string const& msg): 
      std::runtime_error(msg) 
     {} 
}; 

void Transfer(){ 
    try{ 
      throw myException("Error creating the directory\n"); 
    }catch(std::exception &e){ 
     cout << "Exception " << e.what() << endl; 
     //catch an exception which kills the program 
     // the program shall not continue working. 
    } 

} 

另外,如果你不想讓自己的類,你可以簡單地通過

throw std::runtime_error("Error creating the directory\n"); 
+7

通過常量引用來捕獲異常是一個很好的經驗法則。 – 2012-07-24 16:45:00

+1

你明白了。 '拋出std :: runtime_error(「味精」)'會做到這一點。 – cybertextron 2012-07-24 16:50:46

+1

我想補充一點,在各個地方退出程序的可擴展性不是很好。這當然不應該在將成爲圖書館一部分的代碼中完成。最好扔掉儘可能少的地方(例如main)。 – 2012-07-24 16:55:03

6

usage of strtok is incorrect - 它需要一個char*,因爲它修改字符串,但不允許修改在std::string一個.c_str()的結果。需要使用C風格的演員陣容(這裏演奏的像是const_cast)是一個很大的警告。

無論何時發佈,您都可以通過使用boost文件系統(likely to appear in TR2)整齊地避開這個問題和路徑分隔可移植性。例如:

#include <iostream> 
#include <boost/filesystem.hpp> 

int main() { 
    boost::filesystem::path path ("/tmp/foo/bar/test"); 
    try { 
    boost::filesystem::create_directories(path); 
    } 
    catch (const boost::filesystem::filesystem_error& ex) { 
    std::cout << "Ooops\n"; 
    } 
} 

拆分平臺分隔符上的路徑,根據需要創建目錄,或者在失敗時引發異常。