I'm making a heap class and I want one of my functions, const Employee& Heap::top() const, to return a reference to the top element or throw an error if the heap is empty.

I've never used try, catch, or throw statements before so I'm having trouble getting it to work the way I want.

Here is the function def:

const Employee& Heap::top() const // Not Working
{
	try{
		if(mySize > 0)
			return a[0];
		else
			throw "Heap is empty!";
	}catch(char *str){
		cout << "Error: " << str << endl;
	}
}

The function will get to the catch statement if my heap is empty but then it will still return a random value, which I'm guessing is a[0]. Is there a way I can return an error rather than an Employee reference?
I'm hoping to find the correct way of doing this.

Recommended Answers

All 7 Replies

Why do you catch in this function, immediately after you throw? If you remove the try catch in this function, you will have to catch it at the caller's side (and this function will not return). For example:

try {
 myHeap.top()
} catch( const char* e )
{
 cout << "Error: " << e << "\n";
}

I find it personally 'dirty' to throw a bare char*, I always create an Exception class which inherits from std::exception. And when I catch I catch a const std::exception&.

Edit:
if you want to catch in the top function AND make the caller catch as well, you can change the catch block in top to:

catch( const char* str )
{
   cout << ...;
   throw str;
}

To answer your question, I thought that's how try, throw, catch statements worked. This is my first time using try, throw, catch and I'm finding it fairly difficult to understand it from the online guides.

So in your example when you use myHeap.top(), are you leaving it like the original function I had above or is now just returning the top value of the heap(a[0])?

Any more explanation on how this works would be greatly appreciated.

When you throw, the current function that's currently executing will end abruptly (it will not return though).

Then the exception will 'travel' back though the call stack, until it finds a catch block that catches it, when it finds one that catch block will be executed.
After the catch block is done, execution will continue normally starting from after the catch block.

void throwFunction() {
    throw( 5 );
    cout << "This will never be executed\n"; 
}

void callingFunction() {
    throwFunction();
    cout << "This will never be executed\n"; 
}

int main( ) {

    try {
        callingFunction();
            cout << "This will never be executed\n"; 
    } catch( char* str ) {
        cout << "Exception, str: " << str << "\n";
    } catch( int e ) {
        cout << "Exception, number: " << e << "\n";
    }catch( ... ) {
        cout << "Exception that's not an int or char*\n";
    }
}

throwFunction throws an int, so it stops executing. The exception travels back to callingFunction but there are no try/catch blocks around the call to throwFunction. So it travels back to main, where there are try/catch blocks.
It looks at the first block, which catches a char*... it skips this because the exception is an int. The next block catches an int, so that will be executed. After it prints "Exception, number 5" the execution will continue after the full try/catch blocks.

Thank you. That helped clear a lot of things up.

Sorry I have one more question. When I use this function:

const Employee& Heap::top() const
{
	try{
		if(empty())
			throw "Heap is empty! Returning garbage value";
	}catch(char *str){
		cout << str << "\n";
	}
	return a[0];
}

When I compile on my pc using visual studio it works how I would expect. Meaning, if the heap is empty it prints "Heap is empty..." then returns the value in a[0]. But when I compile and run in linux using g++ it says,
terminate called after throwing an instance of 'char const*'
Aborted

Why is this? And how can I make it act the same in linux as is does on my pc?

Look carefully at what it says: it says a 'const char*' was the reason of the termination, and you are catching 'char*'.

I guess the Microsoft compiler doesn't see that as a difference, and g++ does. So just change it to catch( const char* ).

Sorry I didn't spot this before... it is more correct to catch a const char*

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.