2010-10-24 51 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