ApprenticeHacker
ApprenticeHacker

Reputation: 22031

What's the Best Way to handle file and image loading exceptions?

With an exception that there is no solution or alternative to, for example failing to open an image, I usually do something like:

try
{
    img.load_from_file("my_image.png");
}
catch( const image_loading_exception& e )
{
    /* Could Not Load Image: 'my_image.png' ! */
    string err = "Could Not Load Image: " + e.what() + " !"; // 
    pro::message_box::show( err );
}

Now, is this really good error handling? Should I do something more descriptive, or try to resolve the issue. Displaying a error message box is the only thing that I can think of when handling image or file loading failure. What do you guys do?

Upvotes: 4

Views: 424

Answers (2)

Adam Badura
Adam Badura

Reputation: 5339

What you should do strongly depends on the context.

If such code was placed in a handler for say File|Open menu option where you are opening the image file then it seems acceptable.

On the other hand if it was placed deep down in some internals of skinning for your application then most likely this is bad. Firstly you don't know when this will be executed and if a message box is appropriate then. You don't know how often will this be executed (if this is one of 100 images then showing 100 message boxes is not good...). In fatal case this could lead to dead loop if somehow showing the message box (or dismissing it by the user) would lead to executing this code again.

So unless you provide context it is difficult to provide reasonable and useful answer.


Also note that unless you know the details of load_from_file or its guarantees on image_loading_exception contents showing what() to the user is not a good idea. This string will most likely be a technical information (or could be) not useful and not understandable for the user. (On the other hand if this is just a tool application for you or fellow programmers then it could be acceptable - again context!)

Also unless you know image_loading_exception will do that in its what() you could consider capturing typical cases (missing file, access denied, empty file, corrupted file, ...) and show dedicated ("user oriented") message possibly leaving the what() as details hidden by default or logging it somewhere.

Upvotes: 2

BЈовић
BЈовић

Reputation: 64253

It depends what are requirements :

  • if the program can not continue because a critical image is missing, then it should stop the execution and inform the user what happened
  • if the user entered wrong parameter (for example, wrong file name), they should be informed and asked to enter it again
  • if it is something that is not important at all, then just log a message without informing the user

Upvotes: 4

Related Questions