Creating Sensible Error Trapping

This is an update of a post that originally appeared on May 23, 2011.

Errors in software happen. A file is missing on the hard drive or the user presses an unexpected key combination. There are errors of all shapes and sizes; expected and unexpected. The sources of errors are almost limitless. Some developers look at this vastness, become overwhelmed, and handle all errors the same way—by generating an ambiguous exception for absolutely every error that doesn’t help anyone solve anything. This is the worst case scenario that’s all too common in software today. I’ve talked with any number of people who have had to employ extreme effort just to figure the source of the exception out; many people simply give up and hope that someone has already discovered the source of the error.

At one time, error handling functionality in application development languages was so poor that it was possible to give the developer the benefit of a doubt. However, with the development tools that developers have at their disposal today, there is never a reason to provide an ambiguous “one size fits all” exception. For one thing, developers should make a distinction between the expected and the unexpected. Any expected error—a missing file for example—should be handled directly and specifically. If the application absolutely must have the file and can’t recreate it, then it should display a message saying which file is missing, where it is missing from, and possibly how to obtain another copy.

Even more than simply shoving the burden onto the user, however, modern applications have significantly more resources available for handling the error automatically. For example, it’s quite possible to use an Internet connection to access the vendor’s Web site and automatically download a missing application file. Except to tell the user what’s happening when the repair will take a few minutes, the application shouldn’t even bother the user with this particular kind of error—the repair should be automatic.

All of my essential programming books include at least mentions of error handling, debugging, exceptions, and other tasks associated with running code efficiently and smoothly. For example, Part IV of C++ All-In-One for Dummies, 4th Edition is devoted to the topic of debugging. Part V Chapter 3 of this same book talks about exceptions. If you’re a C# developer, C# 10.0 All-in-One for Dummies discusses exception handling in Book I Chapter 9. Book IV Chapter 2 discusses how to use the debugger to find errors. The point is that it’s essential to handle errors in your applications in a manner that makes sense to the users who rely on the application daily and the developers who maintain it.

Note that many of my newer books provide instructions for working with online IDEs, most especially Google Colab. These online IDEs rarely provide built-in debugging functionality, so then you need to resort to other means, such as those expressed in Debugging in Google Colab notebook.

Exceptional conditions do occur. However, even in these situations the developer must avoid the generic exception at all costs. If an application experiences an unexpected error and there isn’t any way to recover from it automatically, the user requires as much information as possible about the error in order to fix it. This means that the application should diagnose the problem as much as possible. Don’t tell the user that the application simply has to end—there is never a good reason to include this sort of message. Instead, tell the user that the application can’t locate a required resource and specify the resource in as much detail as possible. If possible, let the user fix the resource access problem and then retry access before you simply let the application die an ignoble death. Remember this! Any exception that your application displays means that you’ve failed as a developer to locate and repair the errors, so exceptions should be reserved for truly exceptional conditions.

Not everyone agrees with my approach to error trapping, but I have yet to hear a convincing argument to provide unreliable, non-specific error trapping in an application. Poor error trapping always translates into increased user dissatisfaction, increased support costs, and a reduction in profitability. Let me know your thoughts on the issue of creating a sensible error trapping strategy at [email protected].

Accessing a Global String

This is an update of a post that originally appeared on June 30, 2011.

Some examples work well across multiple editions of my book with slight modifications, so if you have the third edition of my book and this code looks familiar, it probably is with small changes. The example in question in this case now appears in Book I Chapter 7 of C++ All-In-One for Dummies, 4th Edition. The example shown in Listings 7-6, 7-7, and 7-8 describes how to declare a global int variable using extern and one reader wanted to extend this example to the string type. The reader had tried several times, but kept getting the following error message (in fact, you can find this same error in Code::Blocks 8.02 and 10.05 and the update in this post works with both versions):

error: 'string' does not name a type

I’m assuming that you’ve already read the discussion about this example (be sure you read the entire section from pages 183 to 185). Creating a fix for this problem isn’t hard, but providing some example code will make things easier to understand. The first issue is to include the required support in main.cpp (shown in Listing 7-6). Here’s an updated version that includes an entry for a string variable named CheeseburgerType.

#include <iostream>
#include <string>
#include "sharealike.h"
 
using namespace std;
 
int main()
{
  DoubleCheeseburgers = 20;
  CheeseburgerType = "Deluxe";
  EatAtJoes();
  return 0;
}

As you can see, you must provide #include <string> and then set CheeseburgerType to a value, which is "Deluxe" in this case. Otherwise, the example works precisely the same as before.

Let’s look at sharealike.h next (Listing 7-7). The following code changes are essential or the example will never work.

#ifndef SHAREALIKE_H_INCLUDED
#define SHAREALIKE_H_INCLUDED
 
using namespace std;
 
extern int DoubleCheeseburgers;
extern string CheeseburgerType;
void EatAtJoes();
 
#endif // SHAREALIKE_H_INCLUDED

Notice the inclusion of using namespace std;. The example will fail to compile without this statement added unless you specify the namespace as part of the type declaration. Once you define this addition, you can create the extern string CheeseburgerType; declaration. Of course, if string were part of another namespace, you’d use that namespace instead.

The final part of the puzzle is to create the required implementation. This part appears in sharealike.cpp (Listing 7-8). Here’s the final piece of the example:

#include <iostream>
#include <string>
#include "sharealike.h"
 
using namespace std;
 
int DoubleCheeseburgers;
string CheeseburgerType;
 
void EatAtJoes() {
  cout << "How many cheeseburgers today?" << endl;
  cout << DoubleCheeseburgers << " " << CheeseburgerType << endl;
 }

As with main.cpp, you must add the appropriate #include. In addition, this part of the example updates EatAtJoes() to include CheeseburgerType in the output. When you run this example, you’ll now see a cheeseburger type in the output as shown here:

The output of the updated version of GlobalVariable shows the kind of cheeseburger.
The output of GlobalVariable now shows the kind of cheeseburger.

Are there any questions on this extension? Please let me know at [email protected]. You can download the updated version of the code as GlobalVariable2 here:

Checking Your Compiler in Code::Blocks

This is an update of a post that originally appeared on April 6, 2011.

Compilers are important because they turn your human-readable source code into executable code that the computer understands. Selecting the right compiler is essential if you want to obtain the best results from your application. Some readers have asked, “Just how do you select a compiler when working with C++ All-In-One for Dummies, 4th Edition?” The book assumes that you’re using the GNU GCC Compiler setting and there isn’t any guarantee another compiler will work with the book’s source code. Use these steps to check your compiler setting.

  1. Open the Code::Blocks application.
  2. Choose Settings | Compiler and you see the Global Compiler Settings dialog box shown here:
    A display of the Global Compiler Settings dialog box in Code::Blocks.
  3. Choose GNU GCC Compiler in the Selected Compiler field as shown in the figure.
  4. Click OK.

You should be ready to work with the book’s code at this point. Let me know if you have any problems choosing the right compiler at [email protected].

Creating Useful Comments

This is an update of a post that originally appeared on November 21, 2011.

A major problem with most applications today is that they lack useful comments. It’s impossible for anyone to truly understand how an application works unless the developer provides comments at the time the code is written. In fact, this issue extends to the developer. A month after someone writes an application, it’s possible to forget the important details about it. In fact, for some of us, the interval between writing and forgetting is even shorter. Despite my best efforts and those of many other authors, many online examples lack any comments whatsoever, making them nearly useless to anyone who lacks time to run the application through a debugger to discover how it works.

Good application code comments help developers of all stripes in a number of ways. As a minimum, the comments you provide as part of your application code provides these benefits.

  • Debugging: It’s easier to debug an application that has good comments because the comments help the person performing the debugging understand how the developer envisioned the application working.
  • Updating: Anyone who has tried to update an application that lacks comments knows the pain of trying to figure out the best way to do it. Often, an update introduces new bugs because the person performing the update doesn’t understand how to interact with the original code.
  • Documentation: Modern IDEs often provide a means of automatically generating application documentation based on the developer comments. Good comments significantly reduce the work required to create documentation and sometimes eliminate it altogether.
  • Technique Description: You get a brainstorm in the middle of the night and try it in your code the next day. It works! Comments help you preserve the brainstorm that you won’t get back later no matter how hard you try. The technique you use today could also solve problems in future applications, but the technique may become unavailable unless you document it.
  • Problem Resolution: Code often takes a circuitous route to accomplish a task because the direct path will result in failure. Unless you document your reasons for using a less direct route, an update could cause problems by removing the safeguards you’ve provided.
  • Performance Tuning: Good comments help anyone tuning the application understand where performance changes could end up causing the application to run more slowly or not at all. A lot of performance improvements end up hurting the user, the data, or the application because the person tuning the application didn’t have proper comments for making the adjustments.

The need for good comments means creating a comment that has the substance required for someone to understand and use it. Unfortunately, it’s sometimes hard to determine what a good comment contains in the moment because you already know what the code does and how it does it. Consequently, having a guide as to what to write is helpful. When writing a comment, ask yourself these questions:

  • Who is affected by the code?
  • What is the code supposed to do?
  • When is the code supposed to perform this task?
  • Where does the code obtain resources needed to perform the task?
  • Why did the developer use a particular technique to write the code?
  • How does the code accomplish the task without causing problems with other applications or system resources?

There are many other questions you could ask yourself, but these six questions are a good start. You won’t answer every question for every last piece of code in the application because sometimes a question isn’t pertinent. As you work through your code and gain experience, start writing down questions you find yourself asking. Good answers to aggravating questions produce superior comments. Whenever you pull your hair out trying to figure out someone’s code, especially your own, remember that a comment could have saved you time, frustration, and effort. What is your take on comments? Let me know at [email protected].

C++ Data Type Usage

This is an update of a post that originally appeared on October 16, 2015.

Originally I provided this post to correct an example in a previous edition of the book. Now I’m providing it to clarify that same example to a greater degree and answer reader input. The Going Overboard section on page 64 of C++ All-In-One for Dummies, 4th Edition talks about the problems that can occur when you try to stuff a number that’s too large into a specific data type. The problem with the example shown:

cout << 12345678 * 100 / 2 * 3 * 3 << endl;

is that while it does display a warning message, the warning really doesn’t get the point across. In order to see the example as originally intended, you need to change the code to read:

long MyLong = 12345678 * 100 / 2 * 3 * 3;
cout << MyLong << endl;

The code will now produce a warning and you can see why in a clearer way, just as described in the book, because the data type isn’t ambiguous any longer. In both cases you see a warning message of:

warning: integer overflow in expression of type 'int' results in '1260587804'

One of the ways to overcome this problem is to ensure that you use the correct sized variable in the first place. The following code doesn’t produce a warning message because of the use of auto (telling the compiler to choose the correct variable type automatically) and ll (telling the compiler to use a long long variable for the calculation).

auto AutoSize = 12345678ll * 100 / 2 * 3 * 3;
cout << AutoSize << endl;

A number of readers were happy that I pointed the problem out, but wanted to see a fix for the problem as well. When you run the example with the additional code, you see outputs of:

1260587804
1260587804
5555555100

Only the third answer is the correct one and it points out the need to pay attention to both warnings and errors as you code. Please let me know if you have any questions or concerns about this example at [email protected].

C++ Switch Statement Using Strings

This is an update of a post that originally appeared on May 13, 2015.

Readers sometimes ask me the same question often enough that I feel compelled to provide the answer on my blog so that everyone has the benefit of seeing it. C++ does have a switch statement, but you need to use a numeric value with it as described in my book, C++ All-In-One for Dummies, 4th Edition (see page 295 for details). A number of C# developers who are also learning to use C++ have asked me about using strings in the switch statement, which is clearly impossible without some fancy programming technique.

Fortunately, I have found a method for implementing switches using strings on CodeGuru. As the author states, it’s not a perfect solution and you may not find it works for you, but it is an ingenious coding technique and you should at least look at it. It’s better than saying the goal isn’t achievable using any means. To get a better idea of the methods other coders have used to overcome this problem, check out online discussions, such as Why switch statement cannot be applied on strings?.

Something I haven’t been asked about very much, but is really important, is the use of other approaches when working with switches, such as expressions. The C++ switch..case Statement article shows how to use expressions with switch statements, while Switch Statement in C/C++ explores some interesting uses of expressions with switches in more detail. The switch statement documentation discusses upcoming changes for C++ 23, but these changes currently don’t appear in my book.

Of course, I’m always on the lookout for other good solutions to reader problems. If you have another solution to this issue of using strings with the C++ switch statement, please contact me at [email protected]. I always want to keep the door open to an even more innovative solutions. In the meantime, keep those e-mails coming!

Checking SQL Server Status

This is an update of a post that originally appeared on November 14, 2012.

A number of my books rely on database access. Today that database access can take many forms, such as the use of .csv files in my AI, machine learning, and deep learning books. However, this post is specific to those books that use Microsoft’s SQL Server on the local system, which is currently limited to C++ All-In-One for Dummies, 4th Edition (optionally) and C# 10.0 All-in-One for Dummies, but could include other books in the future (or you may simply decide to use Microsoft SQL Server with one of my other books).

In order to access any server, the server must be running. It only makes sense that you can’t access something that isn’t listening. The problem is that SQL Server may not start automatically for a number of reasons on your system and that Visual Studio doesn’t always make it apparent that the server isn’t running. You may get a nebulous message when you try to make a connection that doesn’t tell you anything. (No, SQL Server doesn’t start automatically when you make a request for data.) With this in mind, a post of checking the status of SQL Server is important.

Normally, I would tell you to use the tools that come with SQL Server to check the status of the server. However, some versions of SQL Server Express Edition install without the standard tools now, such as SQL Server Management Studio (SSMS). Without access to these tools, it may seem as if checking the server status is impossible. Fortunately, you have other options.

The best way to check the status of SQL Server on your system is to use the Services console found in the Administrative Tools folder of the Control Panel. The Services console is one of a number of Microsoft Management Console (MMC) snap-ins that Windows installs automatically for you. However, to use this console, you must have administrator rights on the target system. Without these rights, you truly are out of luck in checking the status of your SQL Server setup and will need to get an administrator to help you.

Open the Services console by right clicking Start, choosing Run from the menu, typing services.msc in the Open field, and clicking OK. You find a list of all of the services installed on your system in the resulting Services window. Scroll down the list and you should find one or more SQL Server entries like the ones shown here.

The services window contains a list of Windows services installed on the local machine that their status.
Use the Services console to check the status of services on your system.

In order to work successfully with the examples in my book, you should have SQL Server set to start automatically. In addition, when you check the service, you should see Started in the Status column as shown in the screenshot. If you don’t see Started, then highlight the service as shown and click the Start link you see on the left side (not shown in this case because the service is already started).

To make the examples easier to work with, you should also ensure that the SQL Server Browser service is started. This service makes it possible for Visual Studio to find the SQL Server installation on your system. Without this service, you must correctly type the name of the SQL Server installation you want to use when creating a connection, which is both time consuming and error prone.

If you find that you encounter problems making database examples in my books work, please check the status of SQL Server to ensure the service is actually started. Contact me at [email protected] if you experience any other connectivity problems. I may not be able to fix every problem you encounter, but I often have a good idea of what problems you might be seeing on your system and will do my best to help you.

Choosing Variable Names

This is an update of a post that originally appeared on January 17, 2014.

It often surprises me that developers seem to choose completely useless variable names like MyVariable when creating an application. Although MyVariable could be an interesting variable name for an example in a book, it never has a place in any sort of production code. Even then, I try to create book examples with meaningful variable names, especially when getting past the initial “Hello World” example. Variable names are important because they tell others:

  • What sort of information the variable stores
  • When the variable is commonly used
  • Where the variable is used
  • How to use the variable correctly
  • Why the variable is important

In some cases, the variable name could even indicate who created the variable; although, this sort of information is extremely rare. If you never thought a variable name should contain all that information, then perhaps you haven’t been choosing the best variable names for your application.

Even with these restrictions in place, choosing a variable name can be uncommonly hard if you want to maximize the name’s value to both yourself and other developers. Some organizations make the selection process easier by following certain conventions. If you don’t have an organizational style guide for variable naming, modern programming languages like Python commonly provide a style guide for you to use. These style guides often consider a great deal more than simply variable naming and include issues like the amount of indentation to use. In some respects, they become quite draconian in their approach. Other style guides, like the one for C#, are less time consuming to learn, which is a good thing because most developers have better things to do with their time than to learn some of these nitpicky details. A few languages suffer from an abundance of style guides, like C++. It’s best to choose one of them, such as the Google C++ Style Guide, and stick with it.

However, let’s say that you want to create your own style guide for your organization to use because you use multiple languages and having a different style guide for each language seems just a bit absurd, not to mention adding needless complexity. In this case, you need to ask yourself a series of questions to determine how you want the style guide to work, such as these:

  1. What sort of casing do you want to use for what types of variables?
  2. What information does the variable contain (such as a list of names)?
  3. How is the variable used (such as locally or globally, or to contain coordinates, or a special kind of object)?
  4. When appropriate, what kind of information does the variable contain (such as a string or the coordinate of a pixel on screen)?
  5. Is the variable used for a special task (such as data conversion)?
  6. What case should prefixes, suffixes, and other naming elements appear in when a language is case sensitive?

The point is that you need to choose variable names with care so that you know what they mean later. Carefully chosen variable names make it possible for you to read your code with greater ease and locate bugs a lot faster. They also make it easier for others to understand your code and for you to remember what the code does months after you’ve written it. However, most important of all, useful variable names help you see immediately that a variable is being using the wrong way, such as assigning the length of a name string to a coordinate position on screen (even though both variables are integer values). Let me know your thoughts about variable naming at [email protected].

Antiquated Technology Making Developers Faster

This is an update of a post that originally appeared on November 7, 2014.

I often wonder when I create a blog post whether the technology I’m describing will stand the test of time. In this case, I asked whether the reader would like to be able to type application code faster and with fewer keystrokes. The article, The 100 Year Old Trick to Writing at 240 Words Per Minute, probably has some good advice for you—at least, if you’re willing to learn the technique. It turns out that stenography isn’t only useful for court typists and people who print out the text for the hearing impaired on television, it’s also quite useful for developer. Yes, your IDE probably has more than a few tricks available for speeding up your typing, but I guarantee that these tricks only go so far. My personal best typing speed is 110 wpm and that’s flat out typing as fast as my fingers will go.

Since that original post, someone has come out with a book called Learn Plover! that describes how to use this stenographic technique in more detail. There is also a site devoted to Plover now.

Naturally, I haven’t ever used one of the devices mentioned in the article. However, a stenographer named Mirabai Knight has tried one of the devices and reproduced a 140 keystroke Python application using only 50 keystrokes. By the way, she has produced a series of interesting videos that you may want to review if you really think that Plover is for you. I don’t know of any IDE that can provide that sort of efficiency. Of course, it’s one thing for a trained stenographer to produce these sorts of results, but I’d like to hear from any developer who has used the technique to hear about how well it worked for them. Please contact me about your experiences at [email protected]. (Oddly enough, I did hear from at least one developer who uses it successfully.)

The part that interested me most though is that the system, called Plover, is written in Python. (If you want to see Plover in action, check out the video at http://plover.stenoknight.com/2014/10/longer-plover-coding-snippet-in-python.html. A number of Beginning Programming with Python For Dummies, 3rd Edition readers have written to ask me how they can use their new found programming skills. The book contains sections that tell you about all sorts of ways in which Python is being used, but many of these uses are in large corporations. This particular use is by a small developer—someone just like you. Yet, it has a big potential for impacting how developers work. Just imagine the look on the boss’ face when you turn in your application in half the time because you can type it in so much faster? So, Python isn’t just for really large companies or for scientists—it’s for everyone who needs a language that can help them create useful applications of the sort that Python is best suited to target (and I describe all of these uses in my book).

C++ All-in-One for Dummies Errata on Page 188

There is a mistake on page 188 of C++ All-in-One for Dummies, 4th Edition that is based on a supposed April Fool’s prank that was actually initiated on March 26, 2018 (see https://www.modernescpp.com/index.php/no-new-new) and spread throughout the Internet to sites such as: https://www.fluentcpp.com/2018/04/01/cpp-will-no-longer-have-pointers/.  The problem with pranks, especially pranks that linger because the people who perpetuate them haven’t removed them, is that other people tend to believe them, as in this post: https://stackoverflow.com/questions/59820879/are-new-and-delete-getting-deprecated-in-c#. Later, much later, as in the note on the Fluent C++ site, people admit that it was a joke, but still leave the errant material in place.

 After I had discovered that this information was a joke, I had meant to remove two sentences from the book, but somehow they stayed intact.  The two sentences in question appear in the “Understanding the Changes in Pointers for C++ 20” section:

Readers who already know something about pointers need to be aware of the changes in pointers for C++ 20, which is why it appears first. The essential thing to remember as you move to C++ 20 (where new is deprecated) and then to C++ 23 (where new is removed) is that pointers are going to change.

If you find any other references in the book that state that new is deprecated or removed, they too will be modified or eliminated during the next printing. I apologize for any problems that the error has caused, especially to readers who are new to C++, and have submitted an errata to the publisher so that the error is fixed during the next printing. If you have any questions at all about the book, please contact me at [email protected].