Flash
Flash

Reputation: 3011

Exception Handling problem in C++

Hii , I am new to C++ programming and need some help regarding the code i wrote below.... Its a basic exception handling program

#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;                 
}      

When i compile this ... i get this ...

New types may not be defined in a return type at line 11.(at the start of compare function).

Please explain me what is wrong...

Upvotes: 0

Views: 773

Answers (1)

GManNickG
GManNickG

Reputation: 503765

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;               
  }      

Here's how your code should probably look:

#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         
}

Upvotes: 7

Related Questions