Exception Handling

Hello
In exception handling if you have a collection of exception types that are related through inheritance and the catch blocks take in a reference to the object thrown any base-class reference is able to refer to derived-class objects but if you pass it by value a base-class reference shouldn't recognize a derived-class object. But running my program I get the same results passing by value or reference.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string>

using namespace std;

struct animal
{
private:
	int lifespan;
	char * diet;

public:
	animal() : lifespan(0), diet(NULL) {}
	void getlife(int glife) { lifespan = glife; }
	void getdiet(char * gdiet)
	{
		diet = new char[std::strlen(gdiet)+1];
		std::strcpy(diet, gdiet);
	}
	void display()
	{
		cout << "Lifespan of the animal is " << lifespan << endl;
		cout << "Diet of the animal is " << diet << endl;
	}
};

struct bad1
{
	void getstring1() { cout << "Life can't be less than zero.\n"; }
};

struct bad2 : public bad1
{
	void getstring2() { cout << "Diet can't be nothing.\n"; }
};

int main()
{
	animal pet;
	int lifespan;
	char diet[20];

	try
	{
		cout << "What is the lifespan of the animal? ";
		cin >> lifespan;
		if( lifespan < 0 )
		{
			throw bad1();
		}
		pet.getlife(lifespan);

		cout << "What is the diet of the animal? ";
		cin.get();
		cin.getline( diet, 20 );
		if( strcmp( diet, "Nothing" ) == 0 )
		{
			throw bad2();
		}
		pet.getdiet(diet);
	}
	catch( bad2 & b2 )
	{
		b2.getstring2();
	}

	catch( bad1 & b1 )
	{
		b1.getstring1();
	}
	return 0;
}


This work fine but when you swap bad1 catch-block with bad2 catch-block you'll continuously catch bad1 which is too be excepted but when you pass by value you get the same results
1
2
3
4
5
6
7
8
catch( bad1 b1 )
{
	b1.getstring1();
}
catch( bad2 b2 )
{
	b2.getstring2();
}

when the catch blocks are order this way I'm getting the same results.
I'm pretty sure I'm misunderstanding something here.
Sorry for the silliness of the program I was just trying to see the difference between reference vs value with exceptions since a temporary object is created either way.
Thanks for any help.
Try putting cout statements in the constructors, copy constructors, and assignment operators to see what is going on ;)
When I compile the pass by value, I get:
 g++ ex.cpp
ex.cpp: In function ‘int main()’:
ex.cpp:66: warning: exception of type ‘bad2’ will be caught
ex.cpp:62: warning:    by earlier handler for ‘bad1’

EDIT: I think this is a slicing problem.
http://stackoverflow.com/questions/8392866/exception-passed-by-value
http://en.wikipedia.org/wiki/Object_slicing
Last edited on
Topic archived. No new replies allowed.