代码之家  ›  专栏  ›  技术社区  ›  Flash

C++中的异常处理问题

c++
  •  0
  • Flash  · 技术社区  · 16 年前

    HII,我是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 回复  |  直到 16 年前
        1
  •  7
  •   GManNickG    16 年前
    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         
    }