Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.

Bug 360101

Summary: Unnecessary warning 'Catching by reference is recommended' without parameter name in catch block.
Product: [Tools] CDT Reporter: Missing name Mising name <bert>
Component: cdt-codanAssignee: CDT Codan Inbox <cdt-codan-inbox>
Status: RESOLVED WONTFIX QA Contact: Elena Laskavaia <elaskavaia.cdt>
Severity: normal    
Priority: P3 CC: cdtdoug, Deil.Christoph, malaperle, yevshif, zeratul976
Version: 8.0   
Target Milestone: ---   
Hardware: PC   
OS: Windows 7   
Whiteboard:

Description Missing name Mising name CLA 2011-10-06 10:13:14 EDT
Build Identifier: 8.0.0.201109151620

Code Analysis gives the warning: Catching by reference is recommended 'std::bad_cast', even when there isn't a parameter name to reference.

Example:

#include <iostream>
#include <exception>

class B
{};

class A: public B
{};

int main()
{
        A obj;
        try {
                B& other = dynamic_cast<B&>(obj);
        } catch (std::bad_cast) {
                std::cout << "Error casting A to B";
        }
        return 0;
}

I don't think using std::bad_cast& would give any benefit here.

Reproducible: Always

Steps to Reproduce:
1. See example code
Comment 1 Christoph Deil CLA 2012-09-16 13:37:44 EDT
I think it might still make sense to catch by reference in this case.

Try the code below and you'll see that an unnecessary copy is made:
g++ -Wall test_exception.cpp && ./a.out

catch(A&) instead and no copy is made.

Before closing this issue, could one of the C++ gurus please comment if there are valid use cases for not catching by reference?



#include <iostream>
#include <string>

struct A {
	A(void) {
		std::cout << "constructing an A" << std::endl;
		s = "content of A";
	}
	A(const A& other) {
		std::cout << "copying an A" << std::endl;
		s = other.s;
	}

	std::string s;
};

int main() {
	std::cout << "main" << std::endl;
	try {
		throw A();
	} catch(A) {
		std::cout << "catch" << std::endl;
	}
	std::cout << "end" << std::endl;
	return 0;
}
Comment 2 Nathan Ridge CLA 2013-07-18 00:55:47 EDT
I don't know of any valid use cases for catching by reference. I think the warning is fine as it is.
Comment 3 Marc-André Laperle CLA 2013-07-18 01:40:01 EDT
(In reply to comment #2)
> I don't know of any valid use cases for catching by reference. I think the
> warning is fine as it is.

I think you meant for *not* catching by reference?
Comment 4 Nathan Ridge CLA 2013-07-18 02:30:07 EDT
(In reply to comment #3)
> (In reply to comment #2)
> > I don't know of any valid use cases for catching by reference. I think the
> > warning is fine as it is.
> 
> I think you meant for *not* catching by reference?

Yes, sorry. I meant "I don't know of any valid use cases for catching by value."
Comment 5 Nathan Ridge CLA 2016-12-29 18:25:12 EST
Closing per comment 4.