Assertion in different Languages - assertion

I've a question about using assert / assertion.
I saw / used in different languages the directive assert, but I didn't really understand
the sense behind it.
For example for Unit Tests in Java / C# it is used, I can use it, then I get red or green light (true/false) after running tests.
But in low lewel languages such as C what is the sense behind it? Whats happening behind the instruction? Is this something like Exception Handling?
Is if(obj != null" and "assert.notNull(obj) not the same?

Typically in a C environment, assert() is implemented so that the program terminates e.g. with abort() in case the condition is false.
The idea is that assertions check for invariant conditions that must always be true. If not, there's a programming error and the program is best terminated as soon as possible instead of letting it run in an inconsistent state.
It's not really exception handling: The program cannot recover from an assertion failure, and typically assertions are not used for detecting runtime errors such as allocation failures or I/O errors while exceptions are oftenused for such purposes. Some environments with built-in exception handling implement assetion failures as thrown exceptions, though.
Read more on Wikipedia: http://en.wikipedia.org/wiki/Assertion_(computing)

Related

How should I handle exceptions in C++/Qt? [duplicate]

I was talking to a friend of mine that through my new code I didn't treat exceptions, just because I didn't know how to do it in C++. His answer surprised me: "why in the hell would you want to throw excetions?". I asked him why, but he didn't have a satisfying answer, so I googled it. One of the first pages I found was a blog entry, where the guy who posted wasn't totally against exceptions, but a religious war started in the replies: http://weblogs.asp.net/alex_papadimoulis/archive/2005/03/29/396141.aspx
Now I begin to wonder: is it that bad to throw an exception? For a student like I am, is it wrong to learn programming using exceptions as a normal thing? (When I throw exceptions, I catch them in another level of the code to treat them, most of the times). I have a code example, and I want to know what should I do:
int x;
cout << "Type an integer: ";
cin >> x;
Anything that is typed there that is not an integer will trigger an exception already, right? This exception should be treated there. But when I have a possible exception inside a class that is being used elsewhere in the program, should I make this method throw an exception so I can treat it wherever I call it or should I make it return a standard value when it has any problems?
The exception is always good, always bad, or something to be used in "exceptional" situations? Why?
The C++ iostreams classes do not, by default, use exception handling. Generally one should use exceptions for situations where an error can occur, but such errors are "unusual" and "infrequent" (such as a disk failing, the network being down, etc.). For error conditions that you do expect (such as the user providing invalid input), you should probably not use exception handling, unless the logic that needs to deal with this situation is far removed from the logic in which the situation is detected, in which case using an exception is the way to go. There is nothing wrong with using exceptions, and using exceptions where they are merited is definitely good... just avoid using them where if...else works just fine.
As to the why:
Exceptions often provide a simple, elegant way of handling unexpected errors, but:
Exception propagation, depending on the compiler and platform, may be slower than ordinary control flow, so if you can handle the situation locally, then that will be at least as fast... and you especially don't want to slow down the common, expected cases (such as invalid input). Also:
Exceptions require more type information to be present and also require code that is unrelated to throwing or catching exceptions to be "exception-safe" which is why some object to exceptions.
Question 1:
There is no reason not to use exceptions.
Whether to use exceptions or other techniques depends on the situation.
Exceptions are good to use when you can't fix the error locally.
(This should be an exceptional situation :-)
Error codes are good when you can fix the error locally.
Error codes are bad if you have a library that exposes an interface that returns an error code that needs to be manually checked. In the C world forgetting to check the error code was a significant source of problems.
Exceptions are good when you want to force the user of your interface to check for an error. If the user does not explicitly check and compensate; then the exception will propagate until either it is handled or the application exits.
Problems that come with exceptions:
If your code is a combination of C and C++. Functions with C ABI do not contain enough information for exceptions to propagate. Thus throwing an exception across a C function can (depending on the compiler and other factors) cause problems.
If you register a callback functions with a C library that uses C++ code. Then you must make sure that all exceptions are caught in the callback function and not allowed to propagate back to the C-library.
But this is true when combining any two languages. You can only use the most primitive features across language boundaries (and even that can take work if the languages do not align well). Therefore trying to use any advanced features is usually not supported.
Question 2:
C++ streams by default do not use exceptions.
This is because usually you want to handle the problem immediately.
In your example you use input as an example. In this situation you want to check the error and re-request the input.
int x;
cout << "Type an integer: ";
cin >> x;
while(!cin)
{
cin.clear();
std::cout << "Failed: What do you think an integer is? Try again: ";
cin >> x;
}
Note:
Personally I don't like the phrase 'Use exceptions in Exceptional circumstances". To me that is just to vague. vector::at() throws an exception. For me accessing off the end of an array is going to be exceptional (but for Joe student I doubt it will be exceptional (it will happen every second class as the lecturer throws a new curve ball at him/her)).
Thus I prefer the term "When the problem can not be fixed locally". A problem that can not be fixed locally is when something big has gone wrong (resource depletion (memory full throw bad_alloc()), coding error (access beyond array bounds (throw range_check()))) or any number of things that can not be fixed right there.
There is actually a legitimate reason behind why you shouldn't use exceptions.
The problem is when you throw exception across boundaries (e.g. from one DLL and try...catch it in another DLL) sometimes things can go very wrong. I got a slap on the wrist too when I used it in one of my projects.
Just google it you'll find all sorts of post on this topic, at least it was a problem few years ago when I was still a fulltime C++ developer :)
I tend to follow this convention for internal parts of my applications code:
Do not throw exceptions of your own.
Catch any exception that could be expected from your calls to other code inmediately. Treat it accordingly, for example returning an error code, or "false" with the meaning of no success.
However when designing components, I do use component-scope exceptions, like for example, if connecting to a required database (one which is set up by the installer) fails. Or when you try to call any method violating its preconditions. In general, preconditions are expressed with assertions; however, in the public layer of your component, they should be checked and an exception thrown if they are violated, otherwise the caller has a hard job finding what they are doing wrong. (An alternative is of course to use a debug version, in which failed assertions will scream at you; but this is not always practical - distributing two binaries, keeping them up to date, etc.)
In my opinion, the only general rule is to be consistent and write correct code - choose some way to handle the erroneous/exceptional situations, and follow it consistently.
I think exception handling/throwing can be boiled down to the following:
Use RAII (or using in C#, or with in Python) so your code is exception safe.
Catch exceptions if there's a chance to recover from the error, else let them bubble up.
Throw exception only if you have something useful to add.
Consider a hypothetical example where you're using a serial port communication library to communicate with an external sensor of sorts. Furthermore:
The serial port communication library reports errors by throwing exceptions.
The sensor itself can communicate certain error messages through status codes in cases when it's no longer able to acquire data, when it's functioning outside its max/min operating conditions, etc.
You're using RAII (Resource Acquisition Is Initialization), so if the serial port library throws an exception you wouldn't have to worry about releasing any acquired resources.
If the serial port library thrown an exception, you can:
Catch the exception and try to recover from it somehow, e.g. by reinitializing the library.
Catch the exception, wrap it in your own, and then throw the new exception up the call stack.
Option #1 is unlikely in most cases. And option #2 would probably not add any valuable information to what's already in the original exception.
So usually it's best to allow original exception to bubble up (this is again assuming the RAII is in place and no clean up is needed).
On the other hand, if the sensor itself reports an error code, then it makes a lot of sense to throw your own exception.
This one is also a very interesting and controversial reading on the argument:
http://blogs.msdn.com/b/oldnewthing/archive/2005/01/14/352949.aspx
Throw an exception if, and only if, the alternative is failure to meet a post condition or to maintain an invariant.
That advice replaces an unclear subjective decision (is it a good idea) with a technical, precise question based on design decisions (invariant and post conditions) you should already have made.
If you just blindly go and say I won't use exceptions it means you're not going to use most of the STL. That means you need to write your own classes for strings/vector etc etc ...
Plus exceptions are a much cleaner way of doing error handling (IMHO) and if you already do RAII then adding exceptions is not much harder.
Read everything in Section 14 upto section 14.2 of Bjarne Stroustrup: "C++ programming Language Third Edition"
It is the most convincing answer I have come across.

Should I add exception-handling to existing code base?

I'd like to know the advantages and disadvantages of adding exception-handling to existing code.
I work on a SDK that controls h/w cards in a Windows environment.
The SDK is made of more than 100 DLLs that interact with each other. Our existing code base probably contains 100 000s (if not 1 000 000s) of lines of code. Our modules are also heavily multi-threaded.
We link with the proper library so that we use nothrow new (lic.lib instead of licp.lib).
Most of the code doesn't have exception handling. The code is written with that in mind.
int *p = new int[size];
if (p == NULL)
{
// handle this case...
// most probably return an error code
}
char *q = new char[size];
if (q == NULL)
{
delete[] p;
// handle this case...
// most probably return an error code
}
We also use the RAII technique. For instance, we have a object created on the stack that automatically waits on and releases a critical section.
We want to improve the stability of our SDK. We were thinking of adding exception handling but I'm not convinced that it is the right way to improve the stability. I have to admit that I don't have much experience with EH.
The code, in general, checks for divide by 0 or checks for NULL pointers before dereferencing it. But, it still happens that such a case will happen. Since divide by zero or dereferencing a NULL pointer don't throw an exception, I am wondering how much useful is it to go thru 100 000s of lines of code and add exception handling which will change the workflow and may cause memory leaks if not handled properly. I experimented with SEH but I don't think it makes sense to start using SEH and it is Microsoft specific, isn't it?.
In my mind, I think that if it would be more useful to review the existing code and simply check for possible crashes such as divide by zero that may have been missed.
Also, if I were to add exception-handling, how would I proceed? Modify all the modules at once or start from the bottom-up (meaning, if Module A calls Module B which calls Module C, I would modify C, then B then A since we release our software quite frequently and we would probably only have time to modify C before the next release).
Thank you!
I'd like to know the advantages and disadvantages of adding exception-handling to existing code.
You don't say what you mean precisely by "exception handling", so I'll start with something fundamental: standard C++ (you tagged the question as c++) requires you to write code that "handles exceptions", for all but trivial applications, otherwise your code is faulty. Various parts of the C++ standard library are permitted to throw exceptions, including the new that your sample code uses. Therefore your code is already likely to have the possibility that exceptions could be thrown within it, which it must "handle". What happens in that case? Basically, you must write "exception safe code".
It is an error for a program to leak resources in the face of exceptions. You use RAII so you should be OK.
It is an error for any object to enter an inconsistent state after an exception is throw. Ensuring that can be much more tricky.
You should first focus on making your code exception safe.
With Legacy code, you should introduce exception handling in a few places as schedule permits; either the least accessed areas of the code (to reduce the risk of errors to the rest of the code base) or to where they would produce the most benefit (citical error places).
I do not recommend stalling a legacy project just to add exception handling everywhere. The hardest part about legacy code is to modify it and keep it working. After all, its been tested and its behavior is well documented.
I agree with Raedwald that if you are using C++ without a very careful coding standard to avoid EH (ex: using nothrow new, avoiding standard containers, etc), which I'm assuming the legacy code did not, then the code is already broken and is likely to leak and do sporadic things already in the face of exceptions it can already encounter like bad_alloc or bad_cast if you rely on dynamic_cast.
That said, from a very pragmatic standpoint with a legacy codebase, chances are that the legacy code managed to get away with it. And after all, how many non-trivial applications can gracefully recover from bad_alloc exceptions without very explicit control over memory allocation? Not many, and it doesn't cause the entire world to come to a screeching halt.
So I actually don't recommend rewriting the legacy code to try to catch exceptions and use RAII everywhere. You might utilize RAII here and there in code you absolutely have to modify, but I'd try to look for reasons not to change it too much. Write tests for it and try to stabilize it and turn it into a black box; a library of functionality to be used, not maintained and changed while wading through endless LOC indefinitely.
Now the main reason I pitched in here and resurrected this old thread (apologies!) is because of this comment:
The code, in general, checks for divide by 0 or checks for NULL
pointers before dereferencing it. But, it still happens that such a
case will happen. Since divide by zero or dereferencing a NULL pointer
don't throw an exception [...]
In my strong opinion, you should not throw in response to things like null pointer access or divide by zero because those are programmer errors. Unless you're working in a mission-critical software where you want to gracefully recover even if the software is buggy in order to try to reduce the risk of costing lives or something like that, you don't want the application to gracefully recover in the event of programming mistakes. The reason you generally don't want to do that is because it has the downside of hiding bugs, making them silent, allowing users to ignore and work around them and maybe not even bother reporting them.
Instead for programmer mistakes you should generally favor assert which doesn't involve exceptions at all. If the assertion fails, the software in a debug build will come to a halt and typically display an error message telling you where the assertion failed down to the precise line of code. That is usually the quickest bet to detecting and fixing these programming mistakes when running a debugger in response to a bug report, so feel free to assert liberally.
Exceptions are most useful for external exceptional events outside of a programmer's control. An example would be reading a file that turns out to be corrupt. That's not within the programmer's control to handle so there it's appropriate to throw and recover. Another example is failing to connect to a server, a user jamming an abort button for an operation that is supposed to finish, etc. Those are exceptional external input events, not programmer mistakes.
The best way to recover from programmer mistakes like null pointer accesses and divide by zeros is to first detect them (assert is handy), write a test to reproduce it, fix it and get the test to pass, and call it a day, not throw exceptions and catch them while leaving those mistakes in there.

Where to put Assertions?

Having assertions for unexpected conditions is considered to be good defensive coding practice. I happen to place assertions whenever i think something unexpected may happen, but that now seems to be an overkill to me.
Additionally, sometimes mild unexpected conditions that don't necessarily lead to crash may even cause failure on customer end.
Is there a hard and fast rule to put assertions?
Thanks.
The main difference between when to use assertions and exceptions:
Use an assertion to catch programming errors. Assertions should never happen if the code has been written correctly.
Use exceptions to catch run-time errors caused by unexpected environment.
If your program reads a script or contents from a file and they do not match the expected format, I consider that is a runtime condition therefore an exception.
You may decide, for debugging purposes, to use an assertion in the place where an exception is thrown simply to be able to work out more easily where it got thrown, although you can use exception macros that insert FILE and LINE into the message to do that too.
Where to put assertions?
What is often overlooked is that an assert can also serve as a documentation aid.
So don't only test for the 'unexpected', also use them to express your assumptions (invariants) at critical points in your code. Like assert(high >= low)
And of course make them conditional, as others have pointed out here.
No there is not... but I would definitely recommend treating assertions differently in test and production.
It is perfectly okay, in a test environment, to produce a core dump. It allows easy inspection of the conditions that triggered the assertion by nicely safe keeping the whole state of the program.
However in a production environment, you never want to crash (except in case of memory corruption...). The user is expecting the system to always respond, there is nothing more irritating that requesting something and never receiving a response. Therefore it is your job to ensure that the user gets the more meaningful response possible, even if it is an error message. The simplest way to achieve this is usually to throw an exception.
Assertions are put when you are very sure that some conditions have to be true before going to the next level of your code. For example when a window handle is invalid or when some varible is not having a valid value.
from the sounds of it, you leave them enabled in release builds. if so, create levels of assertions - those that will be enabled or disabled in certain builds. then just use an assertion level.
this way, you don't need to turn them down, off, or remove them for development and debug builds or beta releases.
i typically disable them in release, but they do consume a ton of written code. i don't think it's bad - it serves as documentation and enforces the interface to be used as intended. i think it's good to have what many devs may consider too many assertions, but there really aren't too many in the big picture because codebases evolve and this ensures that the programs are always used as intended. therefore, i don't recommend removing them, just disable the non-fatal checks for release builds.
ultimately, there are better approaches than levels (see discussion below and take what you want from others' responses) - but levels are one simple way to introduce the change without affecting existing programs considerably. this would be a good approach for a transition to another error handling scheme, or if you're >98% happy with what you have already.

When should assert() be used?

In developing a large C++ programming project with many developers, we have run into issues with inappropriate use of assert() in the code which results in poor quality where the assertion does indeed occur and the product crashes.
The question is what are good principles to apply to use assert() appropriately? When is it proper to use an assert() and when is it not? Is there a list of criteria that each assertion should pass in order to be legitimate? How can we encourage proper use of assert()?
As a first crack at this, I would say that assert() should only be used to document a condition that is believed to be impossible to reach and which should be identified as an assert() failure at run time where it ever to arise because programming assumptions are being violated.
Can folks do better than this? What is your experience with assert()?
Use Exceptions for error condition which come from the outside (outside the method or outside the program) like parameter checking and missing/defective external ressources like files or connections or user input.
Use Assertions to indicate an internal defects like programming errors, conditions that shouldn't occur, e.g. class/method invariants and invalid program state.
You should use assert to check all conditions that should never happen:
Preconditions on input parameters
Results of intermediate calculations
Postconditions on object state
But you should include those asserts only in debug builds or when explicitly activated for release (not in builds released to the customers).
I use asserts to check for any unwanted program state:
Function preconditions
Sometimes I insert them in a macro after every API call: glDrawArray(); checkOpenGLError();--checkOpenGLError() will call getGLError() if turned on
Data structure integrity: assert(something == null);
Sometimes GDB lies to me (iOS SDK 3.2). I use asserts to prove it.
Note that "unwanted program state" excludes errors that naturally occur at runtime, such as being unable to open a user-selected file due to permissions or HD failure. In these cases it is not wise to use assertions.
Much code nowadays has a lot of external dependencies and connections. I don't tend to use traditional assertions much these days, I favor exceptions. I don't feel like I can assume "this can never happen" and the checks can safely be removed in a non-debug build.

To throw or not to throw exceptions?

I was talking to a friend of mine that through my new code I didn't treat exceptions, just because I didn't know how to do it in C++. His answer surprised me: "why in the hell would you want to throw excetions?". I asked him why, but he didn't have a satisfying answer, so I googled it. One of the first pages I found was a blog entry, where the guy who posted wasn't totally against exceptions, but a religious war started in the replies: http://weblogs.asp.net/alex_papadimoulis/archive/2005/03/29/396141.aspx
Now I begin to wonder: is it that bad to throw an exception? For a student like I am, is it wrong to learn programming using exceptions as a normal thing? (When I throw exceptions, I catch them in another level of the code to treat them, most of the times). I have a code example, and I want to know what should I do:
int x;
cout << "Type an integer: ";
cin >> x;
Anything that is typed there that is not an integer will trigger an exception already, right? This exception should be treated there. But when I have a possible exception inside a class that is being used elsewhere in the program, should I make this method throw an exception so I can treat it wherever I call it or should I make it return a standard value when it has any problems?
The exception is always good, always bad, or something to be used in "exceptional" situations? Why?
The C++ iostreams classes do not, by default, use exception handling. Generally one should use exceptions for situations where an error can occur, but such errors are "unusual" and "infrequent" (such as a disk failing, the network being down, etc.). For error conditions that you do expect (such as the user providing invalid input), you should probably not use exception handling, unless the logic that needs to deal with this situation is far removed from the logic in which the situation is detected, in which case using an exception is the way to go. There is nothing wrong with using exceptions, and using exceptions where they are merited is definitely good... just avoid using them where if...else works just fine.
As to the why:
Exceptions often provide a simple, elegant way of handling unexpected errors, but:
Exception propagation, depending on the compiler and platform, may be slower than ordinary control flow, so if you can handle the situation locally, then that will be at least as fast... and you especially don't want to slow down the common, expected cases (such as invalid input). Also:
Exceptions require more type information to be present and also require code that is unrelated to throwing or catching exceptions to be "exception-safe" which is why some object to exceptions.
Question 1:
There is no reason not to use exceptions.
Whether to use exceptions or other techniques depends on the situation.
Exceptions are good to use when you can't fix the error locally.
(This should be an exceptional situation :-)
Error codes are good when you can fix the error locally.
Error codes are bad if you have a library that exposes an interface that returns an error code that needs to be manually checked. In the C world forgetting to check the error code was a significant source of problems.
Exceptions are good when you want to force the user of your interface to check for an error. If the user does not explicitly check and compensate; then the exception will propagate until either it is handled or the application exits.
Problems that come with exceptions:
If your code is a combination of C and C++. Functions with C ABI do not contain enough information for exceptions to propagate. Thus throwing an exception across a C function can (depending on the compiler and other factors) cause problems.
If you register a callback functions with a C library that uses C++ code. Then you must make sure that all exceptions are caught in the callback function and not allowed to propagate back to the C-library.
But this is true when combining any two languages. You can only use the most primitive features across language boundaries (and even that can take work if the languages do not align well). Therefore trying to use any advanced features is usually not supported.
Question 2:
C++ streams by default do not use exceptions.
This is because usually you want to handle the problem immediately.
In your example you use input as an example. In this situation you want to check the error and re-request the input.
int x;
cout << "Type an integer: ";
cin >> x;
while(!cin)
{
cin.clear();
std::cout << "Failed: What do you think an integer is? Try again: ";
cin >> x;
}
Note:
Personally I don't like the phrase 'Use exceptions in Exceptional circumstances". To me that is just to vague. vector::at() throws an exception. For me accessing off the end of an array is going to be exceptional (but for Joe student I doubt it will be exceptional (it will happen every second class as the lecturer throws a new curve ball at him/her)).
Thus I prefer the term "When the problem can not be fixed locally". A problem that can not be fixed locally is when something big has gone wrong (resource depletion (memory full throw bad_alloc()), coding error (access beyond array bounds (throw range_check()))) or any number of things that can not be fixed right there.
There is actually a legitimate reason behind why you shouldn't use exceptions.
The problem is when you throw exception across boundaries (e.g. from one DLL and try...catch it in another DLL) sometimes things can go very wrong. I got a slap on the wrist too when I used it in one of my projects.
Just google it you'll find all sorts of post on this topic, at least it was a problem few years ago when I was still a fulltime C++ developer :)
I tend to follow this convention for internal parts of my applications code:
Do not throw exceptions of your own.
Catch any exception that could be expected from your calls to other code inmediately. Treat it accordingly, for example returning an error code, or "false" with the meaning of no success.
However when designing components, I do use component-scope exceptions, like for example, if connecting to a required database (one which is set up by the installer) fails. Or when you try to call any method violating its preconditions. In general, preconditions are expressed with assertions; however, in the public layer of your component, they should be checked and an exception thrown if they are violated, otherwise the caller has a hard job finding what they are doing wrong. (An alternative is of course to use a debug version, in which failed assertions will scream at you; but this is not always practical - distributing two binaries, keeping them up to date, etc.)
In my opinion, the only general rule is to be consistent and write correct code - choose some way to handle the erroneous/exceptional situations, and follow it consistently.
I think exception handling/throwing can be boiled down to the following:
Use RAII (or using in C#, or with in Python) so your code is exception safe.
Catch exceptions if there's a chance to recover from the error, else let them bubble up.
Throw exception only if you have something useful to add.
Consider a hypothetical example where you're using a serial port communication library to communicate with an external sensor of sorts. Furthermore:
The serial port communication library reports errors by throwing exceptions.
The sensor itself can communicate certain error messages through status codes in cases when it's no longer able to acquire data, when it's functioning outside its max/min operating conditions, etc.
You're using RAII (Resource Acquisition Is Initialization), so if the serial port library throws an exception you wouldn't have to worry about releasing any acquired resources.
If the serial port library thrown an exception, you can:
Catch the exception and try to recover from it somehow, e.g. by reinitializing the library.
Catch the exception, wrap it in your own, and then throw the new exception up the call stack.
Option #1 is unlikely in most cases. And option #2 would probably not add any valuable information to what's already in the original exception.
So usually it's best to allow original exception to bubble up (this is again assuming the RAII is in place and no clean up is needed).
On the other hand, if the sensor itself reports an error code, then it makes a lot of sense to throw your own exception.
This one is also a very interesting and controversial reading on the argument:
http://blogs.msdn.com/b/oldnewthing/archive/2005/01/14/352949.aspx
Throw an exception if, and only if, the alternative is failure to meet a post condition or to maintain an invariant.
That advice replaces an unclear subjective decision (is it a good idea) with a technical, precise question based on design decisions (invariant and post conditions) you should already have made.
If you just blindly go and say I won't use exceptions it means you're not going to use most of the STL. That means you need to write your own classes for strings/vector etc etc ...
Plus exceptions are a much cleaner way of doing error handling (IMHO) and if you already do RAII then adding exceptions is not much harder.
Read everything in Section 14 upto section 14.2 of Bjarne Stroustrup: "C++ programming Language Third Edition"
It is the most convincing answer I have come across.