2010-10-24 50 views
0

斐伊川處理的問題,我是新來的C++編程,需要有關我下面寫的代碼一些幫助.... 它是一種基本的異常處理程序異常在C++

#include<iostream> 

class range_error 
{ 
     public: 
    int i; 
    range_error(int x){i=x;} 
} 

int compare(int x) 
    { 
       if(x<100) 
        throw range_error(x); 
      return x;    
    }     

int main() 
    { 
    int a; 
    std::cout<<"Enter a "; 
    std::cin>>a; 
    try 
     { 
     compare(a);   
     } 
     catch(range_error) 
     { 
      std::cout<<"Exception caught"; 
      } 
     std::cout<<"Outside the try-catch block"; 
    std::cin.get(); 
    return 0;     
}  

當我編譯這個.. 。我得到這個...

新類型可能沒有在第11行的返回類型中定義(在比較函數的開始處)。

請給我解釋一下什麼是錯的...

+1

我希望你的代碼是不實際的格式,它隨機。 – GManNickG 2010-10-24 07:14:50

回答

7
class range_error 
{ 
     public: 
    int i; 
    range_error(int x){i=x;} 
}; // <-- Missing semicolon. 

int compare(int x) 
    { 
       if(x<100) 
        throw range_error(x); 
      return x;    
    }  

下面是你的代碼也許應該看看:

#include <iostream> 
#include <stdexcept> 

// exception classes should inherit from std::exception, 
// to provide a consistent interface and allow clients 
// to catch std::exception as a generic exception 
// note there is a standard exception class called 
// std::out_of_range that you can use. 
class range_error : 
    public std::exception 
{ 
public: 
    int i; 

    range_error(int x) : 
    i(x) // use initialization lists 
    {} 
}; 

// could be made more general, but ok 
int compare(int x) 
{ 
    if (x < 100) // insertspacesbetweenthingstokeepthemreadable 
     throw range_error(x); 

    return x;    
}     

int main() 
{ 
    int a; 
    std::cout<<"Enter a "; 
    std::cin>>a; 

    try 
    { 
     compare(a);   
    } 
    catch (const range_error& e) // catch by reference to avoid slicing 
    { 
     std::cout << "Exception caught, value was " << e.i << std::endl; 
    } 

    std::cout << "Outside the try-catch block"; 
    std::cin.get(); 

    return 0; // technically not needed, main has an implicit return 0   
} 
+0

謝謝。這是有幫助的。但是如何通過引用捕獲避免切片......請解釋... – Flash 2010-10-24 07:33:30

+0

@ravi:如果另一個類派生於'range_error'類,(也許提供了一個不同的'what()'函數) ,如果你被價值捕獲,那個對象就被「切割」了;它失去了多態行爲。另外,通過引用捕捉避免了不必要的副本。這是一個很好的習慣。 (它不一定是const引用。) – GManNickG 2010-10-24 08:00:42

+0

它不一定是const,但它可能應該是。 – 2010-10-24 16:54:56