2014-06-12 33 views
0
try 
{ 
    bool numericname=false; 
    std::cout <<"\n\nEnter the Name of Customer: "; 
    std::getline(cin,Name); 
    std::cout<<"\nEnter the Number of Customer: "; 
    std::cin>>Number; 
    std::string::iterator i=Name.begin(); 
    while(i!=Name.end()) 
    { 
     if(isdigit(*i)) 
     { 
      numericname=true; 
     } 
     i++; 
    } 
    if(numericname) 
    { 
     throw "Name cannot be numeric."; 
    } 
} catch(string message) 
{ 
    cout<<"\nError Found: "<< message <<"\n\n"; 
} 

爲什麼我得到未處理的異常錯誤?即使我添加了catch塊來捕獲拋出的字符串消息?未處理的異常,即使在添加try-catch塊之後? C++

+0

像'抓(字符* MSG)'或'捕捉(爲const char * MSG)' –

+0

(字符*消息)試sometihng工作! :D但是之前的代碼有什麼問題?我確實添加了#include

+0

並且非常感謝,它工作了! –

回答

3

"Name cannot be numeric."不是std::string,這是一個const char*,所以你需要趕上這樣的:

try 
{ 
    throw "foo"; 
} 
catch (const char* message) 
{ 
    std::cout << message; 
} 

搭上「富」,因爲你需要投擲/抓住它這樣std::string

try 
{ 
    throw std::string("foo"); 
} 
catch (std::string message) 
{ 
    std::cout << message; 
} 
+0

謝謝,它工作! –

1

你應該發送一個std::exception而不是像throw std::logic_error("Name cannot be numeric") 然後你可以用polymorphsim來捕獲它,並且拋出的基礎類型不會成爲問題:

try 
{ 
    throw std::logic_error("Name cannot be numeric"); 
    // this can later be any type derived from std::exception 
} 
catch (std::exception& message) 
{ 
    std::cout << message.what(); 
}