Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are exceptions thrown when arguments are passed by value [duplicate]

I have a type throwing when copied:

struct A { A(const A&) { throw 1; } };

void doit(A)
{
}

int main()
{
    A a;
    doit(a);
    return 0;
}

Is the exception thrown inside or outside of the function? Can I declare the function as noexcept?

like image 614
Martin Fehrs Avatar asked Mar 25 '20 20:03

Martin Fehrs


People also ask

What is an argument exception?

argument exception. ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method.

Is it rude to throw exceptions for invalid arguments?

Throwing exceptions for invalid arguments is rude, unless you write a library. Assertions don't need to be tested, while throw assertions do, and test against ArgumentNullException looks ridiculous (try it).

Why do I get argumentoutofrangeexception when passing a value?

ArgumentOutOfRangeException is thrown when a method is invoked and at least one of the arguments passed to the method is not null reference ( Nothing in Visual Basic) and does not contain a valid value. So, in this case, you are passing a value, but that is not a valid value, since your range is 1–12.

Is illegalargumentexception a checked exception?

Although Java's argument exception ( IllegalArgumentException) is not a checked exception (and rightly so), so I'm not sure what he is referring to. Show activity on this post. If you can code your method or its signature in such a way that the exception condition cannot happen, doing so is arguably the best approach.


1 Answers

See C++17 [expr.call]/4

... The initialization and destruction of each parameter occurs within the context of the calling function. [ Example: The access of the constructor, conversion functions or destructor is checked at the point of call in the calling function. If a constructor or destructor for a function parameter throws an exception, the search for a handler starts in the scope of the calling function; in particular, if the function called has a function-try-block (Clause 18) with a handler that could handle the exception, this handler is not considered. — end example ]

So the exception is, as you would put it, thrown "outside of the function". You can declare it noexcept.

like image 106
Brian Bi Avatar answered Oct 02 '22 14:10

Brian Bi