Throwing exceptions

Feb 7, 2016 at 11:12pm
Hello, I'm trying to write a function that will return an element from an array. Now, it can happen that this array is empty, so nothing can be returned, and that is where I wan't to throw exception, but I can't get it to work.

Here it is:

1
2
3
4
5
6
7
class underflowError: public baseException
{
	public:
		underflowError(const string& msg = ""):
			baseException(msg)
		{}
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int pqqueue::top()
{
	int i = MAXPRIORITY;

	if(empty())
    {
        throw(underflowError("Queue is empty!\n"));
    }

    while(i != 0)
    {
        i--;
        if(!priority[i].is_empty())
        {
            int tmp;
            tmp = priority[i].get_front();
            pqsize -= 1;
            return tmp;
        }
    }
};


In main:
1
2
3
4
5
6
7
8
    int pop = que1.top();
    try
    {
        cout << pop << endl;
    } catch (underflowError& ufE)
    {
        cout << ufE.what() << endl;
    }


This is not working. Can I get some help please?
Last edited on Feb 7, 2016 at 11:13pm
Feb 7, 2016 at 11:16pm
cout << pop << endl;

What is pop?

Edit: I see you've edited things.

Now look at this code:
1
2
3
4
5
6
7
8
 int pop = que1.top();
    try
    {
        cout << pop << endl;
    } catch (underflowError& ufE)
    {
        cout << ufE.what() << endl;
    }


Which line of this code are you expecting to throw an exception? Is it a line of code inside the try block?
Last edited on Feb 7, 2016 at 11:18pm
Feb 7, 2016 at 11:17pm
Updated my first post. Noticed that this line was missing. Thanks for noticing.
Feb 7, 2016 at 11:19pm
Which line of this code are you expecting to throw an exception? Is it a line of code inside the try block?
Feb 7, 2016 at 11:21pm
Oh, now I notice it! But it still causes program to crash (when I move pop = que1.top(); to try block)
Feb 7, 2016 at 11:38pm
Just managed to get it working. I had a probem in my 'empty()'. Sorry for all of this trouble.
Feb 7, 2016 at 11:39pm
I don't know what baseException is, but the following code throws and catches a custom exception without any trouble (C++11).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <exception>
#include <string>
#include <iostream>

using namespace std;

class underflowError: public exception
{
	public:
string message;
		underflowError(const string& msg = "")
				{message = msg;}
 const char* what() const noexcept {return message.c_str();}

};

int main()
{
  
    try
    {
        throw (underflowError("beans"));		
    } catch (underflowError& ufE)
    {
        cout << ufE.what() << endl;
    }
}
Topic archived. No new replies allowed.