Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have seen many exception handling mechanisms where they simply weren't necessary. A lot of the times the problem could have been solved in a much cleaner way using simple if statements.
For example, things like:
Invalid input
Division by zero
Wrong type
Container range check
Null pointer
Uninitialized data
... and so on.
Could someone provide an example where it would be a better approach to handle exceptions?
Exceptions become more important as your program size grows.
With a simple application return codes are probably fine. But when an error condition needs to bubble up a couple levels of the stack before being handled, it starts to make sense to use exceptions instead of passing error codes from every function.
Also, when a method already returns a value, it may not be practical or possible to return an error code from the function as well.
Sometimes using exception is cleaner. In function foo thanks to exception throwing in check function you can avoid checking what check returns what makes this function simpler:
#include<iostream>
using namespace std;
class A{
public:
int a_foo(int index){return _tab[index];}
private:
static int _tab[3];
};
int A::_tab[3]={1,2,3};
void check(int index)
{
if (index < 0 || index > 2)
throw string("invalid index");
}
void foo(A a, int index){
check(index);
cout << a.a_foo(index) << endl;
}
int main()
{
try
{
A a;
foo(a,4);
}
catch(string ex)
{
cerr << ex <<'\n';
}
}
I would use it when the consequence of some unexpected 'event' is inability for application to continue running. When it happens and you catch it, report it nicely and close the application (or whatever you think you should do in that case).
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In C many functions return int if they need to let the calling code know if something went wrong in a function call.
C++ has exceptions which do the same thing but more formalized by the language. One advantage (or sometimes disadvantage) of returning an int instead is that you don't force the calling code to address when something has gone wrong, so it can ignore the warning if it doesn't matter in the context
Is it bad practice in C++ to return an int to indicate that something has gone wrong. Additionally, if it is bad practice what are better alternatives.
Is it bad practice in C++ to return an int to indicate that something
has gone wrong. Additionally, if it is bad practice what are better
alternatives.
Yes, it's terrible practice. If there is an error, always throw an exception. Unchecked errors are a pointless source of bugs, they work really poorly in certain language constructs like constructors, and they're hard to reason about in generic code.
If the operation succeeded but with some warning, you could consider using an enumeration (not int!) for the warning, although typically such operations can return multiple warnings.
i'd recommend a enum class for errorCodes, that way you do not accidentally mix them up with other errors or some actual int values
e.g.
enum class MyResultCode
{
NoError = 0,
InternalError,
DatabaseError,
}
as user4581301 suggested, you can add NumberErrors as a last enum value and accompany the enum class with some human-readable strings. This way you can log or display a nice error message
One of the main advantages of exceptions is, that you can isolate error handling code from business logic. Say you have a long chain of functions and the last function in the chain has to return an error:
int funcA()
{
try
{
return funcB();
}
catch(...)
{
// handle exception
}
}
int funcB()
{
return funcC();
}
int funcC()
{
// do some stuff
}
If an exception is thrown in funcC the exception will propagate to the closest try/catch block. Since there is not an immediate try/catch in funcC, all objects created in funcC will be destroyed and then it will move to funcB to look for a try/catch block and the same process will repeat. So by the time we hit the top level caller, the stack will be unwound so all objects created in the stack will be safely disposed of. Basically we handled the exceptional code only in one place funcA(). Also by using exceptions, you get contextual information as to what happened, for example:
int divide(int a, int b)
{
if(b == 0)
{
throw "Division by zero error";
}
return a / b;
}
With custom error codes, you to propagate the error manually all the way to the top so we will end up with error handling code in every layer:
// using error codes
int funcA()
{
int ret = funcB();
if(ret == someErrorCode)
{
return someErrorCode;
}
else
{
// do some stuff
return goodValue;
}
}
int funcB()
{
int ret = funcC();
if(ret == someErrorCode)
{
return someErrorCode;
}
else
{
// do some stuff
return goodValue;
}
}
int funcC()
{
// do some stuff
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am writing code C++ code in Xcode. At an instance I'm making sure that all fields are valid.
SomeClass *myclass = new SomeClass();
std::string myString;
if ( (myClass) && (myString.c_str)) {
return true;
} else {
return false;
}
Should i be checking for testString.c_str? Does it makes sense?
The default behavior of the new() operator is to either return the new object, or throw an exception if memory allocation failed. So, you don't need to check if myClass is NULL, unless you set the flags to change the behavior or implemented your own new() operator for your class.
Also, the extra brackets around myClass are not necessary. A better way to express what you want to check would be
if ((myClass != nullptr) &&
Then, you are currently testing if the address of the method c_str() in the std::string class is not NULL. Not want you want to do, I guess.
First, you would need to write myString.c_str(). Then, this method never returns a NULL pointer, what it can return is an empty C string. But this is better tested with std::string::empty(), so your check would look like this:
if (myString.empty()) {
return false;
} else {
return true;
}
which can of course be shortened into
return !myString.empty();
Finally: If you have this code in a function/method: Who deletes your new SomeClass object?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am working on an object-oriented C++ coursework where I need to return error codes from the main function. How would one do this properly?
Unfortunately this is an assessed coursework so I cannot post my code here. But let's say the case is as follows:
I'm building an enigma machine with classes Plugboard, Reflector, and Rotor. I pass each of the configuration files as arguments in the command line. In this task, I'm provided with a file errors.h containing the following:
#define INSUFFICIENT_NUMBER_OF_PARAMETERS 1
#define INVALID_INPUT_CHARACTER 2
#define INVALID_INDEX 3
// and so on...
So I have in my program several functions to check the errors, for example a function to check whether the configuration file contains an invalid character (it has to be 0 to 25). I was thinking of setting this as a boolean function and then in my main function have the following:
if (!plugboard.check_invalid_character(/*some arguments*/)) {
cerr << "Invalid character!" << endl;
return 2;
}
But I'm not completely sure this is the right way to do it? Is it too superficial? Is there a more elegant way of returning error?
I hope my question is a little clearer this time. Thanks before.
You just need to return the value 4 in your main method like this:
int main() {
return 4;
}
Please note that your main function could also have the arguments vector and the argument count so there could be more in the brackets.
If KLibby is right and you use a method with returns the value you need to use something like that:
int doSomething() {
return 4;
}
int main() {
return doSomething();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
When ı use goto in class in c++ ,I faced to that message,how can ı use goto in class c++?
In member function `void note_system::student_no()':
label 'stop' used but not defined`
You would do something like this (to have a single scope exit point, say when for some exotic reason using a RAII-based trick is not possible):
status_code func_with_goto() {
if (i_see_errors()) goto func_end;
...
func_end:
return status_code::error;
}
Or like this (to emulate break-by-label-like behavior):
outer: while (...) {
inner: while (...) {
...
goto outer;
}
}
Or if you just want to reimplement your second Basic program from 80-th in C++:
x10: std::cout << "Hello World!" << std::endl;
x20: goto x10;
There are very few cases where goto may be justified. Its presence complicates static code analysis by both humans and compilers. This does not mean at all that goto should be banned, it should just be use with double care.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
How do I have main() remember the value of a variable each time it is called?
i.e. if I run this program the first time I want mainCallCounter = 0, but when I is called again I want it to increase the counter
#include <iostream>
using namespace std;
static int mainCallCounter = 0;
void outputMainCallCount()
{
cout << "Main was called" << mainCallCounter << "times." << endl;
}
int main()
{
outputMainCallCount();
mainCallCounter++;
return 0;
Main is the entry point for your program. Main is called once (normally) and, when it exits, your program is torn down and cleaned up.
Obviously this means a local variable will be insufficient. You need some sort of external storage which persists longer than your application, i.e., the file system.
You can't. Each run of a program is independent. You will need to save mainCallCounter somewhere and re-read it the next time the application launches. Writing it into a file is one option, another might be something like the Windows registry or Mac OS X defaults system, etc.
All variables declared in C++ expire when the program ends. If you want to persistently remember how many times the program has been run, you will need to store that data in an external file and update it whenever you run the program.
For example:
#include <iostream>
#include <fstream>
int numTimesRun() {
std::ifstream input("counter.txt"); // assuming it exists
int numTimesRun;
input >> numTimesRun;
return numTimesRun;
}
void updateCounter() {
int counter = numTimesRun();
std::ofstream output("counter.txt");
output << counter;
}
int main() {
int timesRun = numTimesRun();
updateCounter();
/* ... */
}
Hope this helps!