Catch all type of assertion - c++

I need a condition like:
try
{
//bug condition
}
catch()
{
//Remove file
}
That is I create one very confidential file which data cannot be viewed by third party, but when any bug occurred in code my file is deleted because I don't known exactly, where bugs occurred.
So I want to catch that bug using try and catch and want to delete that file. How can I catch any exception in C++??
That will delete file if there is a bug.
Like:
try
{
char TempArray[10];
char c = TempArray[11];
}
catch
{
cout<<"Array out of boundry";
deleteFile("Confi.txt");
}

A word about security: If you create a file, on hard disk, with confidential information, anyone can shut down the computer while the process is running and the file is still open, take out the hard drive and read its contents.
If the file is on the server you can do basically the same thing by pausing your process before it deletes the file.
Even if you removed the file from the filesystem, most likely it can still be read, since removing a file does not wipe its contents.
I'd recommend not to deal with confidential information until you have the needed expertise - not by learning from SO. But if you have to do it, I think the watchdog process suggested here + encryption is the way to go.

FIRST OF ALL:
You don't want to do that.
Exceptions are not meant for handling bugs, but run-time error conditions that make it impossible for your function to satisfy the pre-conditions of other functions it has to call, or to keep the promise of fulfilling its own post-conditions (given that the caller has satisfied the pre-conditions). See, for instance, this article by Herb Sutter.
Don't ever write anything like this:
try
{
//bug condition <== NO! Exceptions are not meant to handle bugs
}
catch()
{
//Remove file
}
But rather:
assert( /* bug condition... */ );
BACK TO THE QUESTION:
Your program has undefined behavior, and most likely it will not throw any exception at all when you do:
char TempArray[10];
char c = TempArray[11];
So catching all exceptions won't help. This is a bug, i.e. a programming error, and it is arguable whether you should handle bugs in a way that transfer controls to a buggy routine; moreover, if you are admitting the presence of bugs in your program, couldn't you just be transferring control to a buggy handler? That may make it even worse.
Bugs should be dealt with by preventing them, making use of assertions, perhaps adopting methodologies such as test-driven development, and so on.
This said, regarding a way to catch all exceptions, you can do:
try
{
// ...
}
catch (...) // <== THIS WILL CATCH ANY EXCEPTION
{
}
But using catch (...) is discouraged as a design guideline, because it easily leads to swallow error conditions that are meant to be handled and forget about them. After all, exceptions were invented exactly to prevent programmers to forget checking error codes, and catch (...) makes that so easy.
For a catch-everything purpose, it would be better to let all of your exceptions derive from std::exception, and then do:
try
{
// ...
}
catch (std::exception& e)
{
// Do something with e...
}

What you want to use is RAII. In this case create class which in constructor take name of file and in destructor it delete the file. Before doing anything with the file you instantiate object of such class with appropriate name and later on if for whatever reason the function exits (cleanly or by means of exception), the file is going to be deleted.
Example code:
class FileGuard : public boost::noncopyable {
std::string filename_;
public:
FileGuard(const std::string &filename) : filename_(filename)
{}
~FileGuard()
{
::unlink(filename_);
}
}

Your code attempts to access data outside the defined boundaries, which is in all essence a completely valid thing to attempt. Depending on situation and compiler, your code may or may not crash with an access violation/segfault, most probably not. It will most certainly not raise an exception - in C++ exceptions are only thrown explicitly by code, not implicitly by the system, it just crashes if it goes wrong unlike higher level languages like Java and C#.
The catch(...) syntax will catch every possible exception, but this is not applicable in this situation.

As the other answers alluded to, you cannot correctly solve this problem with native, standard c++. Infact, trying to do anything once undefined behaviour has occurred is normally a really bad thing. If you do not know the state your app is in, how can you possibly and safetly run code? Just fail fast.
The proper way to solve your problem is to have another, separate 'watchdog' process performing your clean up. Its pretty simple - just have the watchdog process constantly monitor for the existance of the file. When it pops into existence the watchdog process should delete it. This delete will pend until the last reference to the file exists and then it will perform the deletion [on *nix OS's it will rename the file to a temporary place, on Win systems it will just wait until the file is unreferenced]. Once the main program is finished with the file - either through normal means or crashing or whatever, the OS will delete the file for you correctly.

If you want to make sure your 'private' file is always removed, how about a 'wrapper' program.
Create a new application that runs your protected application and then waits for it to terminate. When it terminates (however that is, crash or clean exit), delete your private file then exit.
Instead of running your application, run the wrapper.
int main(void)
{
int processId = exec("your protected app");
WaitForProcessExit(processId);
_unlink("protectedfile.bin");
return 0;
}

C++ allows you to work directly with the memory and is partly C compatible. The syntax you are trying to use:
char some_array[10];
Is kind of C syntax, not C++ and
char c = some_array[11];
is raw access to memory. This is unexpected behavior. That means that no one will tell you what is going to happen. Maybe you just get wrong character and maybe you program will be killed by OS. Or the moon will fall on the Earth. =)
If you want high level features - use pure C++. Look at standard library instead of "C" arrays. You can use std::vector with at (size_type n) method to get out_of_range exception - just like you need.

Related

How throw, try {} catch {} should be used in the real world?

I mean, I knew all the language rules about throw, try {} catch {}, but I am not sure if I am using them correctly in the real world. Please see the following example:
We have a large piece of scientific code which did all sorts of image processing things, recently we decided to spruce it up and make it more robust. One of the routines which is frequently used is void rotate_in_place(float* image, image_size sz);
To make it more robust, we add some sanity check at the beginning of the code:
void rotate_in_place(float* image, image_size sz) {
// rotate_in_place does not support non-square image;
if (sz.nx != sz.ny) throw NonSquareImageError;
// rotate_in_place does not support image too small or too large
if (sz.nx <= 2 || sz.nx > 1024) throw WrongImageSizeError;
// Real rode here
.....
}
Now the problem is that rotate_in_place() is used in over 1000 places, shall I wrap each call of rotate_in_place() with try{} catch {}, this looks to me will make code incredibly bloated. Another possibility is do not wrap any try{} catch{} and let the program exit, but how is this different from just using
if (sz.nx != sz.ny) {
cerr << "Error: non-squared image error!\n";
exit(0);
}
In short, I am not so sure about the real benefit of using throw, try, catch, any good suggestions?
Every site that handles the error needs try-catch block. It all depends on your design, but I doubt you need to handle the error in every rotate_in_place call-site, you probably get away from propagating upwards most of the time.
Printing the error and using exit is bad for three reasons:
You can't handle the error. exit is not handling (unless it's done when the error is absolutely critical, but your function cannot know that — caller might have a way to recover).
You're extending responsibilities of the function with writing to a hard-coded stream, which might not even be available (this is rotate_in_place, not rotate_in_place_and_print_errors_and_kill_the_program_if_something_is_wrong) — this hurts reusability.
You lose all debugging information with this approach (you can generate stack traces from unhandled exceptions, you can't do anything with a function that bails out every time — unhandled exception is a bug, but it's a bug you can follow to the source).
The general rule for exceptions is, "Does the immediate call site care about what's going on here?" If the call site does care, then returning a status code probably makes sense. Otherwise, throwing makes more sense.
Consider it this way -- sure, your rotate in place method has a couple of invalid argument types, in which case you should probably throw std::invalid_argument. It's unlikely that a caller of rotate_in_place wants to deal with or knows how to deal with the case that an image was not square, for example, and therefore that's probably better expressed as an exception.
Another possibility is do not wrap any try{} catch{} and let the
program exit, but how is this different from just using
if (sz.nx != sz.ny) {
cerr << "Error: non-squared image error!\n";
exit(0);
}
It's different because if someone later wants to take your function and put it in, say, a GUI application, they don't have to terminate the program based on the error. They can turn that exception into something pretty for the user or something like that.
It also has benefits for you right now -- namely that you don't have to pull <iostream> into that translation unit simply to do error writing.
I usually use a pattern something like this:
int realEntryPoint()
{
//Program goes here
}
int main()
{
//Allow the debugger to get the exception if this is a debug binary
#ifdef NDEBUG
try
#endif
{
return realEntryPoint();
}
#ifdef NDEBUG
catch (std::exception& ex)
{
std::cerr << "An exception was thrown: " << ex.what() << std::endl;
}
#endif
}
Now the problem is that rotate_in_place() is used in over 1000 places, shall I wrap each call of rotate_in_place() with try{} catch {}, this looks to me will make code incredibly bloated.
It will, and it beats the purpose of using exceptions in the first place.
Another possibility is do not wrap any try{} catch{} and let the program exit, but how is this different from just using [...]
That you can always change the location of exception handling later on. If at some point you find a better place to sensibly handle the error (perhaps recovering from it), then that's the point where you put the catch. Sometimes that's in the very function where you throw the exception; sometimes it's way up in the call chain.
Do put a catch-all in main, just in case. Deriving exceptions from standard ones such as std::runtime_error makes doing this a lot easier.
The point in using exception handling holds in following simple rules:
As soon as anything bad can happen due to bad user input (internal logic should be handled via assertions/logging), throw an exception. Throw as soon as possible, and as much as possible: C++ exceptions are usually pretty cheap compared to say, .Net ones.
Let an exception propagate if you can't handle the error. This means pretty much always.
The thing to remember is: The exception should bubble up to the point where it can be handled. This can mean a dialog box with some formatting of the error, or this can imply that some unimportant piece of logic won't be executed after all, etc.
Using exceptions allows the caller to decide how to handle an error. If you called exit directly within the function, then the program would exit without the caller being able to decide how to handle the error. Also, with exit, stack objects would not be unwound. :-(
What you can do is to make rotate_in_place return a boolean if the function call was succesfull. And return the rotated image via a function parameter.
bool rotate_in_place(float* image, image_size sz, float** rotated_image) {
// rotate_in_place does not support non-square image;
if (sz.nx != sz.ny) return false;
// rotate_in_place does not support image too small or too large
if (sz.nx <= 2 || sz.nx > 1024) return false;
// Real rode here
.....
return true;
}
It depends.
Exceptions are generally meant to be caught/handled. In your case, is it possible to handle the exception (for instance, the user provides a non-square image, so you ask them to try again). However if there is nothing you can do about it, then cerr is the way to go.
Well, I agree that really using Exceptions results in bloated code. That is the main reason for me not liking them.
Anyway, as to your example: The key difference between throwing exceptions and just using exit() is that, since the handling of the exception happens (or is supposed to happen) outside of the program fragment that generated the error/exception, you do not specify how the user of a function/class has to handle the error. By using exceptions you allow different treatments like aborting the program, reporting errors or even recovering from certain errors.
TLDNR: If you use exceptions, the exception-generating part of the code does not need to specify how the exceptional case is treated. That happens in the outside program and can be changed depending on how the code is being used.

Complete code in try/catch block

I want to know, is it a good practice to place complete code inside a try block or I should place only the code which I feel it will cause a specific exception?
And should I catch basic Exception always
Code 1: complete code in try block
myFunction(){
try{
.........
Code with chance of OneException
.............
}catch(OneException e){
............
}catch(Exception e){
..............
}
}
Code 2: Only the Code with chance of Exception in try block
myFunction(){
.......
try{
Code with chance of OneException
}catch(OneException e){
............
}
............
}
Code 3:Should I catch Exception always
myFunction(){
.......
try{
Code chance of OneException
}catch(OneException e){
............
}catch(Exception e){
..............
}
........
}
Out of this (code1, code2 and code3) which one is the best?
I'm mainly concern with java and C++ coding
Generally speaking, you should only catch exceptions you're interested in and which you can handle. That is...catch an exception where you can do something s.t. the user doesn't perceive the problem or when it is explicitly necessary to tell the user about the problem.
For all other exceptions, let them pop up with all their details (stacktrace etc..) which you obviously log. Note, obviously this doesn't mean the user should also see that exception output but rather a generic error.
Told this, I assume that when you write "Code chance of OneException" you know how to handle OneException, but not Exception, right? So then...only handle OneException.
Always catch exactly what you have to and no more. No matter how much we try, we cannot make our code completely "idiot proof". If someone passes you something which will cause some random error, then it is their job to handle it. If our code handles someone else's exception that has far too much risk of being an unexpected side-effect.
As far as what code to place where: code before the line which could throw the Exception will be run either way, so it does not really make sense to have it inside the try block and before the code which throws. Code after the potential exception should be placed between try and catch if and only if it depends on the exception generating code. So, if your database connection call can fail, place all of the database queries inside the try block.
Limiting the "time" spent in a try...catch makes it easier to read and less prone to accidental catching. I can't tell you how many hours have been lost because someone decided to catch an Exception which should have propagated.
a) It is bad practice, to place complete code inside a try block.
a1) Beside of catching exceptions, a try-block is a documentation where an exception might happen. So place it close to the cause, you have in mind.
a2) In bad circumstances, you have a file for reading, and add later one for writing, but your exception (FileNotFoundException) was written only with the first in mind. A lean scope around the problematic places will help you, identifying further problems.
b) Don't catch basic Exception for completeness or to avoid multiple catch blocks. If you want to write to a file, many things can go wrong: Missing permission, illegal file name, no space left on device, ... . If you present the user a generic Message ("Couldn't write file " + name), he doesn't know what to do. Be as specific as possible, and you can inform him, "Only 20 MB left on device " + devicename + "We need another 8 MB (28 MB in total); please free some space and repeat or choose a different device!"). If you catch "Exception", chances are high, that you're thinking of some exception, but another one occurs, and isn't handled correctly, because the catch-block wasn't written with that possibility in mind.
The best chance to find this exception is, to let it pop up, or, to log it, if the logs are controlled on a regular basis.
It can be a difference between developing an application, which is simply used by end users, or by developing an API, which is used by other developers.
In an API, you often want to wrap an exception into an own exception, to make it easier for users of your api to handle it, and if you have an uniform way to handle exceptions. If your code can throw many exceptions, and would lead to ugly client code, where your customer would need to specify a bunch of exceptions over and over again, you often wrap the exceptions and rethrow them:
try {
...
}
catch {FileNotFoundException fnfe}
{
throw new MyApiException (fnfe);
}
catch {PermissionDeniedException pde}
{
throw new MyApiException (pde);
}
catch {IOException ioe}
{
throw new MyApiException (ioe);
}
That way, your client can decide, how to handle the exception, and will find the specific type of exception, if interested, inside your exception.
As Landei points out, in Java 7 there will be a simplified technique, to catch multiple exceptions, but not only such with a common superclass, see this link here
Wrap the code at the point where you really can handle the exception, and where you can handle the error. If you can't handle the error in the function, then do no wrap the code in try/catch block.
I don't know for java, but in c++ you should catch by const reference :
try
{
// code that can throw an exception
}
catch ( const SomeExceptionType & error )
{
// handle the error
}
C++ isn't Java or C# or... where you need catch (or finally) clauses to clean up after yourself. In C++, RAII does that. Consequently, I rarely ever write try/catch statements in C++, to the point where I consider it a code smell.
So, rather than contemplating which style of code you should use in conjunction with try/catch, you should ask yourself whether you need that try/catch at all.

How to change my error handling method

I can't seem to get my head around why people say C++ exceptions are better. For example, I have an application which loads function objects from shared objects to be used in the application. What goes on is something like this:
bool LoadFunctions()
{
//Get Function factory.
FunctionFactory& oFactory = GetFunctionFactory();
//Create functions from the factory and use.
}
FunctionFactory& GetFunctionFactory()
{
//Get shared object handle.
void* pHandle = dlopen("someso.so");
//Get function ptr for Factory getter.
typedef FunctionFactory* (*tpfFacGet)();
tpfFacGet pF = static_cast<tpfFacGet>(dlsym(pHandle, "GetFactory"));
//Call function and return object.
return *((*pF)());
}
Now, it's easy to see that loads of stuff can go wrong. If I did it like I always do, I'd return pointers instead of references, and I'd check if they were NULL and print an error message and get out if they weren't. That way, I know where things went wrong and I can even try to recover from that (i.e. If I successfully load the factory and fail to load just a single function, I may still continue). What I don't understand is how to use exceptions in such a scenario and how to recover the program rather than printing an error message and qutting. Can someone tell me how I am to do this in C++ish way?
We don't even need return codes. If a problem occurs it should be in the exception.
int main()
{
try
{
LoadFunctions();
// if we're here, everything succeeded!
}
catch(std::exception _e)
{
// output exception message, quit gracefully
}
// IRRESPECTIVE OF SUCCESS/FAILURE WE END UP HERE
return 0;
} // eo main
EDIT:
Okay, so lets say that you have an alternative method of loading functions should LoadFunctions() fail. You might be tempted to call that in the catch handler, but this way you'll quickly end up with a huge amount of nested exception handlers which just complicates things.
So now we get down to the question of design. LoadFunctions should succeed if functions are loaded and throw out an exception if it does not. In this hypothetical example of an alternative method of loading functions, that call should be within the LoadFunctions method. This alternative method does not need to be visible to the caller.
At the top level we either end up with functions, or we do not. Writing good exception handling, in my opinion is about getting rid of grey areas. The function did what it was told to do, or it didn't.
There is, as you say, a lot that can go wrong. You won't catch a bad cast there by the way. If the symbol exists but is not the type you are casting it to, you will just get a nasty shock later.
If you were to avoid exceptions you will need somewhere to report the error. As your LoadFunctions and GetFunctionFactory() do not know how you wish to handle the error (log it? print it to stderr? Put up a message box?) The only thing it can do is generate the error.
A common way do to that in C is to pass in a parameter into which it can put the error if one occurs, and for each function to "check" success before continuing. This can make the flow rather tricky.
The C++ concept of "throwing" the exception means that you do not need to keep passing a pointer (or reference) through each function. Where the error occurs you generate it and "throw" it - a bit like "shouting" it. This causes all code (other than cleanup in destructors) to halt until it finds a catcher that handles the error the way that is required.
Note that exceptions should only generally be used to handle errors, not a normal occurrence like encountering "end of file" when this is the way you know a read has completed.
Using exceptions instead of return-values (or any other method) is not supposed to change the behaviour of the code, only how it is written and organized. That means basically that first you decide what your recovery of a certain error is, be it more graceful or less, then you write the code to perform that.
Most experienced programmers (all practically) agree that exceptions are a much better method than return values. You can't see the big difference in short examples of a few functions, but in real systems of thousands of functions and types you would see it clearly. I will not get into more details of how it is better.
I suggest anyway you should just get yourself used to using exceptions by default. However note that using exceptions has some somewhat delicate issues (e.g. RAII http://en.wikipedia.org/wiki/RAII), that ultimately make your code better, but you should read about them in a book (I won't be able to describe here and feel that I do justice to the subject).
I think the book "Effective c++ / Scott Meyer" deals with that, certainly "Exceptional C++ / Herb Sutter". These books are a good jump start for any c++ developer if you havent read them anyway.

Risking the exception anti-pattern.. with some modifications

Lets say that I have a library which runs 24x7 on certain machines. Even if the code is rock solid, a hardware fault can sooner or later trigger an exception. I would like to have some sort of failsafe in position for events like this. One approach would be to write wrapper functions that encapsulate each api a:
returnCode=DEFAULT;
try
{
returnCode=libraryAPI1();
}
catch(...)
{
returnCode=BAD;
}
return returnCode;
The caller of the library then restarts the whole thread, reinitializes the module if the returnCode is bad.
Things CAN go horribly wrong. E.g.
if the try block(or libraryAPI1()) had:
func1();
char *x=malloc(1000);
func2();
if func2() throws an exception, x will never be freed. On a similar vein, file corruption is a possible outcome.
Could you please tell me what other things can possibly go wrong in this scenario?
This code:
func1();
char *x=malloc(1000);
func2();
Is not C++ code. This is what people refer to as C with classes. It is a style of program that looks like C++ but does not match up to how C++ is used in real life. The reason is; good exception safe C++ code practically never requires the use of pointer (directly) in code as pointers are always contained inside a class specifically designed to manage their lifespan in an exception safe manor (Usually smart pointers or containers).
The C++ equivalent of that code is:
func1();
std::vector<char> x(1000);
func2();
A hardware failure may not lead to a C++ exception. On some systems, hardware exceptions are a completely different mechanism than C++ exceptions. On others, C++ exceptions are built on top of the hardware exception mechanism. So this isn't really a general design question.
If you want to be able to recover, you need to be transactional--each state change needs to run to completion or be backed out completely. RAII is one part of that. As Chris Becke points out in another answer, there's more to state than resource acquisition.
There's a copy-modify-swap idiom that's used a lot for transactions, but that might be way too heavy if you're trying to adapt working code to handle this one-in-a-million case.
If you truly need robustness, then isolate the code into a process. If a hardware fault kills the process, you can have a watchdog restart it. The OS will reclaim the lost resources. Your code would only need to worry about being transactional with persistent state, like stuff saved to files.
Do you have control over libraryAPI implementation ?
If it can fit into OO model, you need to design it using RAII pattern, which guarantees the destructor (who will release acquired resources) to be invoked on exception.
usage of resource-manage-helper such as smart pointer do help too
try
{
someNormalFunction();
cSmartPtr<BYTE> pBuf = malloc(1000);
someExceptionThrowingFunction();
}
catch(...)
{
// Do logging and other necessary actions
// but no cleaning required for <pBuf>
}
The problem with exeptions is - even if you do re-engineer with RAiI - its still easy to make code that becomes desynchronized:
void SomeClass::SomeMethod()
{
this->stateA++;
SomeOtherMethod();
this->stateB++;
}
Now, the example might look artifical, but if you substitue stateA++ and stateB++ for operations that change the state of the class in some way, the expected outcome of this class is for the states to remain in sync. RAII might solve some of the problems associated with state when using exceptions, but all it does is provide a false sense of security - If SomeOtherMethod() throws an exception ALL the surrounding code needs to be analyzed to ensure that the post conditions (stateA.delta == stateB.delta) are met.

try all or just what's necessary?

What is better coding practice: if I have to have a try/catch block shall I place everything (every initialization and so on) in this block or just those variables which may throw? Is there any difference between those two constructions?
In example:
Having:
struct A {
A();
int a;
int* b;
};
and later on in .cpp:
A::A() {
a = 5;
try {
b = new int;
}
catch(...){
}
}
or
A:A() {
try {
a = 5; //this time in try block
b = new int;
}
catch(...) {
}
}
is there any difference between those two constructs or is this in a way if I have to have a try/catch block I may aswell put everything in it?
Thank you.
P.S.
For God efin sake, formatting here drives me really crazy! And I know that I mentioned this many times, I'm not going mad.
I think a good general principle is to make a try block as "narrow" as possible -- don't put in it things that you believe won't ever cause exceptions. That way, should you ever be wrong and have one of those "can't cause exception" parts actually do cause an exception, you won't be accidentally "swallowing" the astonishing exception (and no doubt dealing with it in inappropriate ways, since your code would not be expecting that exception but other kinds).
In your code, I would not use a try block at the point you indicate at all. Memory allocation errors are actually both very rare and very difficult to recover from. I would probably catch the exception in main, log the error and exit the program.
More broadly, in C++ you should not wrap every function that could throw in a try block. You should instead write code that can cope with exceptions, using well-known C++ idioms like RAII.
In addition to the very good points by Alex and Neil, the narrow try block makes for an easier to understand code. A future maintainer will know more easily what's going on.
# Alex,
I disagree. You should group logical parts of your program into try catches that should fail or pass as a whole. If something fails, even if you didn't expect it your code should be exception safe and the whole operation should fail and all resources should automatically be released. If you make them narrow then you just end up with tons and tons of try's and catches. Why not just use IF's? (but wasn't that the point of exceptions in the first place? avoid tons of ifs?)
Parashift agrees with me too.
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.12
read 17.12 and 17.13.
Another way to look at this is to include statements in a try block when they all need to succeed or fail together. This way, catch blocks act as a kind of transactional feature in your code. So, you can do something like:
// save current state
try {
// a few statements
// that each modify the state
} catch (e) {
// rollback to original state
}
In your example, assigning to member variable a changes the state of the object, so it should be inside the try block.
In my code, I rarely ever catch anything, except in main(). If you feel like you need catch blocks to clean up after yourself, you do something wrong and need to have a good look at the RAII idiom. As for anything else - an exception should be thrown under exceptional circumstances only, and it's very hard to come up with something generic and smart to do in exceptional moments.