Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ newbie question--basic error handling using try, throw, catch

I'm trying to understand error handling in C++.

I have read that using try, throw, catch is better style and less complicated than using if statements with return values. But I'm not sure I really understand how try, throw, catch works. I made a simple example below and it would be great to get feedback about any problems or bad style. My goal is to make a function out of the example that checks the results of another calculation.

Here are questions I have about try, throw, catch: (1) Should the catch statement be included in my function? Or should it be somewhere else, like in main() or in the function where the initial calculation is done?

(2) Is it overkill to use try, catch, throw for something this simple (I would like to improve my style)?

(3) If there is an error, I would like to terminate the program. How would I do that? Or does "catch" mean that that is done automatically?

(4) I don't understand the use of cerr. Why not just use cout? Have I used cerr correctly here? Should I also have used it in the if/else statements?

Thanks a lot for any help.

Here's the example I made:

double calculated = 10.2; // from previous calculation
double tolerance = 0.3; // I can set this in this function
double valueWanted = 10.0; // from previous calculation

const int calcError = 5; // I picked this number randomly to use for indicating an error

try
{
   if (fabs(fTargetValue - fCalculated) <= fTolerance)
     cout << "Result is within range.";

   else
     cout << "Failed.";
     throw calcError;
}

catch (const int calcError)
{
   cerr << "The calculation failed.\n" << endl;
}
like image 678
Ant Avatar asked Jan 25 '11 11:01

Ant


People also ask

How do you handle errors in try-catch?

It works like this: First, the code in try {...} is executed. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch . If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err) .

What is the use of try-catch throw in exception handling?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The throw keyword throws an exception when a problem is detected, which lets us create a custom error. The catch statement allows you to define a block of code to be executed if an error occurs in the try block.

How do you use try throw and catch in single program explain with suitable examples?

Example. MyData md; try { // Code that could throw an exception md = GetNetworkResource(); } catch (const networkIOException& e) { // Code that executes when an exception of type // networkIOException is thrown in the try block // ... // Log error message in the exception object cerr << e.

Can we use throw with try-catch?

Q #2) Can we use throws, try and catch in a single method? Answer: No. You cannot throw the exception and also catch it in the same method. The exception that is declared using throws is to be handled in the calling method that calls the method that has thrown the exception.


2 Answers

Well that's a lot of questions. I will try to give you some hints :

(1) Do not include the try-catch in your function. Throwing an exception is done to tell the outer world that something happened. If you can handle the problem in your function, do not throw at all ^^ A good error handling is generally to catch the error ASAP (in the caller) or in a general purpose handler far away like in main, to handle gracefully unhandled errors.

(2) As a rule of thumb, use exception for ... exceptional things. Errors are good candidate for exceptional things. An exception could be thrown for things like overflow or division by zero in a math library. You have to decide, but in general it is good to handle errors with exceptions.

(3) catch do not mean that your program will end. In fact it is the contrary. By catching an exception, you say that you will handle the problem ^^ If you want to terminate, a simple way in a simple program is to not catch exception, as the default behavior for uncaught exception is program termination ^^ Instead, you can explicitly terminate your program in some catch block.

(4) cerr is just like cout, but is a different file descriptor. It means that external programs can differentiate cerr from cout. It is used for error, but that's not really important but for external programs.

my2c

like image 74
neuro Avatar answered Nov 15 '22 00:11

neuro


Ok, firstly your example will throw every time because you do not have scope braces after the else. Therefore, only cout << "Failed."; will be executed and throw calcError will be executed each time, regardless of whether the result was in range or not. Change this to:

else
{
    cout << "Failed.";
    throw calcError;
}

In the event that an exception is throw, the code will begin within the catch block you have defined, stating the calculation failed.

If the result was in range (throw is never called), code will begin executed directly after your catch block.

When you throw a type, that type arrives at the catch handler. This allows you to define catch handlers for different types. In this case, you are throwing (and catching) a const int. That's all good. Generally, we throw std::exception or a derivation of this. Your own exception classes can contain information pertinent to the error. In your case you could include a simple message that it was out of range, or indeed include the const int that failed.

like image 22
Moo-Juice Avatar answered Nov 14 '22 23:11

Moo-Juice