0

I am learning C++ using the resources listed here. In particular, i read about exceptions and want to know if is it valid to omit the return statement of a non-void function/function template that throw as shown below:

Example 1

#include <iostream>
//this function template does not have a return statement
template<typename T>
T func()
{
    int x = 4;
    std::cout<<"x: "<<x<<std::endl;
    throw;
}

int main()
{
  func<double>();
}

Example 2

#include <iostream>
//this function does not have a return statement
int func()
{
    int x = 4;
    std::cout<<"x: "<<x<<std::endl;
    throw;
}

int main()
{
  func();
}

My question is that are example 1 and example 2 valid? Or we have UB/ill-formed.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • Why are you using `throw;` rather than `throw exp;`? Using throw without an object is only really valid from inside a `catch` block (and re-throws the current exception object). Using it outside a catch results in `std::terminate()` being called. – Martin York Dec 29 '22 at 22:17

1 Answers1

1

are example 1 and example 2 valid?

Yes.

Or we have UB/ill-formed.

No.

Is it valid to omit the return statement of a non-void function/function template that throw

Yes. A non-void returning function must either throw or return avalue. It cannot do both at the same time.

So is int func(){ int x = 4; throw; return x;} valid

It's valid. But it never returns a value. Everything after the throw is dead code.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • *"A non-void returning function must either throw or return. It cannot do both **at the same time**."* So is `int func(){ int x = 4; throw; return x;}` valid or invalid? Because in the above given example, we have both `throw` and `return` at the same time. So according to your statement, this should be invalid. If not, can you clarify and perhaps add example **what do you mean by at the same time** in your answer. – Jason Mar 03 '22 at 10:42
  • 1
    _"...A function can terminate by returning or by throwing an exception...."_ https://en.cppreference.com/w/cpp/language/functions In this case `or` means you can do either or both in the code, however the function will only exit by one code path. – Richard Critten Mar 03 '22 at 10:53
  • I would note that the OP is using the wrong type of throw (should throw an expression). – Martin York Dec 29 '22 at 22:16