Exception Handling in c++

Hi,

I'm trying to catch an exception in c++ this way:

try
{
std::vector<string> output;
int bytes = atoi(output.back().c_str());
}
catch(exception)
{
//logic here...
}

but it doesn't work...

So, exception handling in c++ is different than c#, where whatever happens inside the try{} catch(){} is always captured? Will I have to add conditions in every part of my code like this

if(output.length() > 0)
{
int bytes = atoi(output.back().c_str());
}

Thanks for the time
atoi doesn't throw exceptions. atoi is from C and C doesn't even have exceptions. atoi returns 0 on failure which is sometimes inconvenient because atoi("0") will also return 0.

In C++11 you can use std::stoi that throws exceptions on failure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>

int main()
{
	try
	{
		std::vector<std::string> output{"not a number"};
		int bytes = std::stoi(output.back());
		std::cout << "Bytes: " << bytes << std::endl;
	}
	catch(std::invalid_argument&) //or catch(...) to catch all exceptions
	
	{
		std::cout << "Exception caugth!" << std::endl;
	}
}


Also you should not call .back() on an empty vector so you will have to check like you do or use if (!output.empty()). You could do output.at(output.size()-1) to get the last element and it will throw an std::out_of_range exception if output is empty but that is probably ugly.
Last edited on
In general C++ exception handling are "expensive", use it sparingly and when the use case really call for it. C/C++ has a tradition of being lean and mean so most of the times the return int values should suffice.
Ok, I think I understand better exception handling now. Thanks for the answers
Topic archived. No new replies allowed.