Regarding exception handling

Hello,

is there any differences with putting the return statement outside of the try-block(like here), or as the last element within the try block? marked with //
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Date stringToDate(string str) {
       if (str.size() != 10)
              throw "Invalid date format";
       if ((str[4] != '‐') || (str[7] != '‐'))
              throw "Invalid date format";
       struct Date d;
       try {
              d.y = stoi(str.substr(0, 4));
              d.m = stoi(str.substr(5, 2));
              d.d = stoi(str.substr(8, 2));
              //any difference if I return here instead??
       }
       catch (invalid_argument e) {
              throw "Invalid date format"; }
       return d;
}

Hello Pecvx,

I would say yes. When you look at the structure of the function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Date stringToDate(string str)
{
	if (str.size() != 10)
		throw "Invalid date format";
	if ((str[4] != '‐') || (str[7] != '‐'))
		throw "Invalid date format";

	struct Date d;

	try
	{
		d.y = stoi(str.substr(0, 4));
		d.m = stoi(str.substr(5, 2));
		d.d = stoi(str.substr(8, 2));
		//any difference if I return here instead??
	}
	catch (invalid_argument e)
	{
		throw "Invalid date format";
	}

	return d;
}

Providing the if statements work where they are. I am not the expert on this, but I am thinking the if statements should be at the top of the try block. I could be wrong here.

If the try block is passed over in favor of the catch block you would be returning a "Date" structure with no information. Except for the garbage that might be there.

I am guessing that the "Date" structure is defined with "int"s and if these are uninitialized there is no way to know what garbage number is there.

So, yes when the try block has set up the "Date" structure properly return it.

Removing line 15 is likely to generate a warning "that all paths do not return a value" of something like it. This is only a warning and nothing to worry about.

Another alternative would be for the catch block to setup an invalid date like "2019", 1, 1. Then line 15 would work for either the try block or the catch block.

Hope that helps,

Andy
Topic archived. No new replies allowed.