Why do we use a reference in the catch statement?

Why do we use a reference in the catch statement? Down below where it says
catch(MyException &e) . What is the point of using the reference? I've found that without the reference the output is the same. Also, could someone explain what
virtual const char* what() const throw() means exactly. I've used the class exception on this site and I don't really understand what all it does.

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
  #include <iostream>
#include <string>
#include <exception>

using namespace std;

class MyException : public exception
{
public:
	virtual const char* what() const throw()
	{
		return "Something bad happened";
	}
};

class Test
{
public:
	void goesWrong() throw(MyException)     
	{
		throw MyException();
	}
};

int main()
{
	Test test;

	try
	{
		test.goesWrong();
	}
	catch (MyException &e)
	{
		cout << e.what() << endl;
	}

	system("PAUSE");
	return 0;
}
Last edited on
Object slicing.

http://ideone.com/cHmxnR

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
#include <iostream>
#include <string>
#include <exception>

using namespace std;

class MyException : public exception
{
public:
    // exception specifications (throw lists) are deprecated.
    // use the noexcept keyword to indicate a function doesn't throw.
    virtual const char* what() const noexcept    
    {
        return "Something bad happened";
    }
};

class Test
{
public:
    void goesWrong()  // exception specifications are deprecated
    {
        throw MyException();
    }
};

int main()
{
    Test test;

    try
    {
        test.goesWrong();
    }
    catch (exception &e)
    {
        cout << e.what() << '\n';
    }

    try
    {
        test.goesWrong();
    }
    catch (exception e)
    {
        cout << e.what() << '\n';
    }

    system("PAUSE");
}
You really should catch by const ref as there's no chance of changing the caught object.
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
	try
	{
		Test test;
		test.goesWrong();
	}
	catch (const std::exception &e)
	{
		std::cout << e.what() << std::endl;
	}
}
You really should catch by const ref as there's no chance of changing the caught object.

Catching by const reference is kind of like using top-level const in functions. There really isn't much point, but it makes some folks happier.

It isn't like the thrower of the exception is expecting it to return unchanged.
The higher-level exception handler may in fact expect the exception to be rethrown unchanged (this is part of what's called "exception-neutral" when describing a library).
Although I agree that it is much like top-level const on a function definition; it is not part of any interface, it's just a constraint on the body of the handler.
Last edited on
Topic archived. No new replies allowed.