Handling Exception in a class

First of all: I'm a noob to C++ and oop in general, so I would like to thank you for the opportunity to ask noobish questions.

Second: I searched in the forum and in documentation but I couldn't find my answer. But feel free to insult me if my question is very too noob (or is in the wrong place)!

The point:

I'm trying to write an interface to MySQL using MySQL Connector/C++ so I created a class to open a connection to db, launch queries and retrieve results.
Now, I'm in trouble with handling exceptions.

Does it have sense to manage exception for (and in) single method of the class?
If yes, what's the easiest way to do this?
have I to change the retun values of methods to return error code?

Thanks in advance to all the good guy who will answer to me.
To handle any exception use this format:

1
2
3
4
5
6
7
8
try
{
  // code
}
catch(...) // ellipsis
{
  cout << "Exception caught! Something went wrong" << endl;
}


There are other methods of catching specific exceptions also using the <stdexcept> header file.
http://www.cplusplus.com/reference/std/stdexcept/

A simple example of using the exceptions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

double divide(double a, double b)
{
	if(b == 0)
		throw "Divide by Zero";
	return (a/b);
}

int main()
{
	double result;

	double a, b;

	cout << "Enter numerator: ";
	cin >> a;
	
	cout << "Enter denominator: ";
	cin >> b;


	try
	{
		result = divide(a, b);
	}
	catch(char* s)
	{
		cout << "Error: " << s << endl;
		return 0;
	}

	cout << a << "/" << b << " = " << result << endl;

	return 0;
}
Last edited on
Thanks for your answer! Atm my code looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int MyClass:mymethod(some parameter)
{
	try {
		// code
	}
	catch (SQLException &e){
		int error=e.getErrorCode();
		// some other code
	}
	if (error){
		// some assignement
		return 1;
	}
	else {
		// it's all ok
		return 0;
	}
}


What I mean is that I don't want people who will use MyClass to "see" the exception happens.

I'm on the right way?

Thanks
Topic archived. No new replies allowed.