Exception handling

This is a discussion on Exception handling within the C++ Programming forums, part of the General Programming Boards category; I want to have the following Classes for Exception handling: Divide by Zero (DevideByZero) Square root of 1 (SquareRootMinusOne) Stack ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    4

    Exception handling

    I want to have the following Classes for Exception handling:
    Divide by Zero (DevideByZero)
    Square root of 1 (SquareRootMinusOne)
    Stack Overflow

    And these are my other classes for my program Calculator:
    Class Input;
    Class Stack,
    Class Execution;

    This is for example the code for the Class Execution where I want to implement one of my Exception handling classes (DevideByZero).

    Code:
    #ifndef _EXECUTION_
    #define _EXECUTION_
    
    
    class Execution
    {
    public:
    	Execution();
    	~Execution();
    	bool Execute(int operation);
    	double Calculate (double A, double B, char Operator);
    
    };
    
    #endif
    
    
    #include "stdafx.h"
    #include "Execution.h"
    #include "TheStack.h"
    #include <iostream>
    #include <exception>
    
    
    using namespace std;
    
    Execution::Execution()
    {
    }
    
    Execution::~Execution()
    {
    }
    
    double Execution::Calculate(double A, double B, char Operator)
    {
    	double result = 0.0;
    	
    	
        if(Operator == '+')
    	{
    		result = A+B;
    	}
        else if(Operator == '-')
    	{
    		result = A-B;
    	}
    	else if(Operator == '*')
    	{
    		result = A*B;
    	}
    	else if(Operator == '/')
    	{
    		
    		if(B == 0)
    		{
    						
    			cout << "Division by zero." << endl;
                         result = 0;
    		}
            }
            else
    		{
    			result = A/B;
    		}
    		
        }
        return result;
    }
    Execption Devide by Zero

    Code:
    Class DevideByZero
    {
    public:
    DevideByZero()
    	~ DevideByZero()
    	double getNumerator()
    	{
    		return firstNumber;
    	}
    
    	double getDnominator()
    	{
    		return secondNumber;
    	}
    
    	string getMessage()
    	{
    		return message;
    	}
    
    
    private:
    	double firstNumber;
    	double secondNumber;
    	string message;
    
    };
    #endif;
    The exception must be handled when the user enters the number 0 as a denominator. But i do not know how to implement? Can anyone be so kind to give me a hint and the correct syntax?

    Thanks

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,527
    To use exception handling properly, you need an exception class, and another class that the program uses. When runtime errors occur in your program's class, you need to throw() your exception. Then somewhere in your program the exception should be handled with a try/catch block.

    And besides that, you included standard exceptions, but you're not using them. If I wrote your code, I would use it.

    Here's an example for you to work with.
    Code:
    #include <iostream>
    #include <stdexcept> // my compiler's exception header
    
    class DevideByZero : public std::exception {
       public:
       // inherited constructor, destructor, and copy
       virtual const char *what() const throw() {
           return "Cannot devide by zero!";
       }
    };
    
    class Execution {
        public:  
       // default contructor, destructor, and copy
       double Calculate(const double A, const double B, const char Operator)
        throw(DevideByZero);
    };
    
    double Execution::Calculate(const double A, const double B, const char Operator)
           throw(DevideByZero) {
       double result = 0.;
       switch(Operator) {
           case '+':
           result = A + B;  break;
           case '-':
           result = A - B;  break;
           case '*':
           result = A * B;  break;
           case '/':
           if (0 == B)
               throw(DevideByZero());
           else result = A / B;
           break;
           default: 
           result = -1.;  break;
       }
       return result;
    }
    
    int main(void) {
        try {
        Execution math_problem;
        std::cout<<"Two plus three is: " << math_problem.Calculate(2, 3, '+') <<
          std::endl;
        std::cout<<"Seven divided by zero is: " << math_problem.Calculate(7, 0, '/') <<
           std::endl;
        }
        catch (DevideByZero& e) {
            std::cout << e.what() << std::endl;
        }
         std::cin.get();
         return 0;
    }
    Just to be clear, if your functions' signature has a throw(type) statement in it, this tells the compiler that you want to limit the function's exceptions down to a certain type. In my example, I allowed Calculate to throw only DevideByZero exceptions because I was confident that it would be the only type of exception. If you write throw() in a function's signature, you are telling the compiler that the function will never throw any exceptions.

    Constructors and destructors should also never throw exceptions.

    I will answer your questions if you have any!
    Last edited by whiteflags; 05-22-2006 at 12:56 PM.

  3. #3
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Can I ask why constructors can't throw exceptions? C++ FAQ says it's okay

  4. #4
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    Quote Originally Posted by Tonto
    Can I ask why constructors can't throw exceptions? C++ FAQ says it's okay
    constructors SHOULD throw exceptions. As they have no return value, it's the only way they can signal an incompletely constructed object.

    Quote Originally Posted by citizen
    Just to be clear, if your functions' signature has a throw(type) statement in it, this tells the compiler that you want to limit the function's exceptions down to a certain type.
    In practice, a functions exception specification is often little more than documentation. Many compilers ignore it.
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  5. #5
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    You should note that if you throw an error from a constructor, the object's destructor will never be called
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  6. #6
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    Quote Originally Posted by JaWiB
    You should note that if you throw an error from a constructor, the object's destructor will never be called
    which is why you should use resource managing classes (auto_ptr, shared_ptr, vector etc) as members.

    i.e.
    Code:
    class BigNDangerous
    {
    public:
        BigNDangerous()
        : p(new int[100000])
        {
             throw "uh-oh"
        }
    private:
        int* p;
    };
    
    int main()
    {
        try
       {
            BigNDangerous b; 
       }
       catch(...)
       {} // even though we caught the exception we still have a huge memory leak
    }
    
    // or we could do
    class BigNSafe
    {
    public:
        BigNSafe()
        : p(100000)
        {
             throw "uh-oh"
        }
    private:
        vector<int> p;
    };
    
    int main()
    {
        try
       {
            BigNSafe b; 
       }
       catch(...)
       {} // vector cleans up after itself like a good class should
    }
    this is known as the basic guarentee and all your code should strive to emulate this behaviour.

    you may not even care about memory ('who cares about memory? I've got 2 gigs and the os will clean up anyway'), but your users will be pretty annoyed if they find your app has locked their files or acquired all the graphics objects!
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  7. #7
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,527
    Quote Originally Posted by ChaosEngine
    In practice, a functions exception specification is often little more than documentation. Many compilers ignore it.
    It is, in fact, standard behavior. Just because compilers are missing something from the standard doesn't mean you should ignore it and not use it, and what's the harm? If the compiler ignores it, nothing happens that's bad.

  8. #8
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    Quote Originally Posted by citizen
    It is, in fact, standard behavior. Just because compilers are missing something from the standard doesn't mean you should ignore it and not use it, and what's the harm? If the compiler ignores it, nothing happens that's bad.
    because it's a waste of time and energy. Even java acknowledges that exception specifications are more effort than they're worth.

    from http://www.gotw.ca/gotw/082.htm
    Quote Originally Posted by Guru of the week
    Q: When is it worth it to write exception specifications on functions? Why would you choose to write one, or why not?

    A: In brief, don't bother. Even experts don't bother.

    Slightly less briefly, the major issues are:

    Exception specifications can cause surprising performance hits, for example if the compiler turns off inlining for functions with exception specifications.

    A runtime unexpected() error is not always what you want to have happen for the kinds of mistakes that exception specifications are meant to catch.

    You generally can't write useful exception specifications for function templates anyway because you generally can't tell what the types they operate on might throw.

    For more, see for example the Boost exception specification rationale available via http://www.gotw.ca/publications/xc++s/boost_es.htm (it summarizes to "Don't!").
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. signal handling and exception handling
    By lehe in forum C++ Programming
    Replies: 2
    Last Post: 06-15-2009, 10:01 PM
  2. Exception handling in a large project
    By EVOEx in forum C++ Programming
    Replies: 7
    Last Post: 01-25-2009, 06:33 AM
  3. exception handling
    By coletek in forum C++ Programming
    Replies: 2
    Last Post: 01-12-2009, 04:28 PM
  4. is such exception handling approach good?
    By George2 in forum C++ Programming
    Replies: 8
    Last Post: 12-27-2007, 07:54 AM
  5. Signal and exception handling
    By nts in forum C++ Programming
    Replies: 23
    Last Post: 11-15-2007, 01:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21