C++中的异常处理问题

Fla*_*ash 0 c++

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;                 
}      
Run Code Online (Sandbox Code Playgroud)

当我编译这个...我得到这个......

第11行的返回类型中可能未定义新类型(在比较函数的开头).

请解释我有什么问题......

GMa*_*ckG 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;               
  }      
Run Code Online (Sandbox Code Playgroud)

以下是您的代码可能看起来的样子:

#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         
}
Run Code Online (Sandbox Code Playgroud)