Error Handling in Programming

Just like separating out the configuration parameters from the program is important, it is also important to separate the error handling mechanism from general running of the program. There are different ways by which errors are handled by the program.

Errors are of various types. There can be computational errors like Division by Zero, file handling errors like missing files, memory allocation errors and device read or write errors. Depends on the context, an error can be fatal or ignorable. Take for example, if a configuration file is missing, it is a fatal error. The program must terminate and report the error to the user.  Of course, your program can have default values for all the required settings and continue. It is a choice left to the programmers. Some programmers prefer to report the missing file as a warning and continue. Take another example of division by zero. One can always check before the division whether the divisor is zero. If it is a zero, it is reported as an error to the user and the program will continue to work (probably asking for the change in input from the user).

There are various categories of errors and depending on the requirement, we decide what action has to be taken. It is difficult to generalize what must be put in a specific category. But fatal errors normally include the missing of crucial files or libraries, inability to allocate enough memory for computation. There are errors that can be ignored, probably there is a work around for the error. Possible examples include spelling mistakes in a text editor. These are errors with respect to the user, but they don’t have an impact on the software. And often such errors are shown to the user in a light fashioned manner (spelling mistakes underlined red). But spelling mistakes of keywords in a programming language are important errors and can not be ignored, because it will lead to compile time errors. A compiler will return critical errors for such mistakes, but a text editor may not.

Once we have identified the errors and their respective categories, the next step is to determine what action must be taken. The program should

  • Exit
  • Warn the user
  • Signal the user for a change
  • Look for a Workaround
  • Ignore
  • Alert or Email the user
  • Log the errors in a file

So while writing programs, we must

  1. Identify (all) the possible errors
  2. Identify the categories of errors
  3. Action to be taken for every category of error

 

Advertisements

C: Using scanf and wchar_t to read and print UTF-8 strings

We saw how using scanf and char to read UTF-8 strings led us to some strange answers. So now we need to discuss the solution provided by C.

/** Program to read a single character of different language
using wchar_t array and scanf. The program prints back the
string along with its length
*/

#include 
#include 
#include <wchar.h>
#include 

int main() {

    wchar_t string[100];

    setlocale(LC_ALL, "");

    printf ("Enter a string: ");
    scanf("%ls",string);

    printf("String Entered: %ls: length: %dn", string, wcslen(string));

    return 0;
}

Let’s see the various aspects of this program.

  • Use of wchar_t instead of char. wchar_t is used by C to deal with the characters of various locales. Note that there are various locales other than UTF-8, but most of them focus on a particular language. wchar_t corresponds to a wide character. wchar is wider than char (1 bytes), so it can carry a large number of characters of various languages
  • To read and print a wide character string, we use the %ls format. Instead of %s, we use %ls to work with the UTF-8 characters. This directs printf and scanf to do special treatment (call additional functions) to the entered string
  • Use of wcslen instead of strlen to get the length of the string. C library provides the function wcslen to get the length of wide character strings
  • There are different ways by which a locale needs to be treated. For example, in some cases, the locale treatment just involves treatment with date or current representation. But here we used LC_ALL to deal with all the locale specific features.

Let’s see more. I need to first show that I am using UTF-8
$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

On executing the program, I will first enter the English character a
$ ./a.out
Enter a single character and press enter: a
String Entered: a: length: 1

The output is as expected, we entered a single character. So the length is 1

Next, I use the French character é
$ ./a.out
Enter a single character and press enter: é
String Entered: é: length: 1

So we got the length 1 as expected

Let’s try the same experiment with a Chinese letter 诶
$ ./a.out
Enter a single character and press enter: 诶
String Entered: 诶: length: 1

Once again, we got what we were looking for, the length 1.

Thus, we must ensure that we use the UTF-8 string for our softwares. It is also important to use the right functions

C: Using scanf and char to read UTF-8 strings

As businesses are turning global, softwares are made that are intended to meet the global customers. UTF-8 has now become a de-facto standard for use in the web. There are obvious questions that arise in the minds of a C programmer whether C supports UTF-8 and is it possible to read a UTF-8 content. In this example, I show how scanf and char are used to read a UTF-8 string. But at the end of the post you will understand why char is not a good option for working with UTF-8.

/** Program to read a single character of different language
  using char array and scanf and printing the string
  along with its length
*/

#include 
#include 

int main() {

    char string[10];

    printf ("Enter a single character and press enter: ");
    scanf("%s",string);

    printf("String Entered: %s: length: %dn", string, strlen(string));

    return 0;
}

We see that in the program, we declare a char array of length 10, we read a string and then print the string along with its length.

I need to first show that I am using UTF-8
$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

On executing the program, I will first enter the English character a
$ ./a.out
Enter a single character and press enter: a
String Entered: a: length: 1

The output is as expected, we entered a single character. So the length is 1

Next, I use the French character é
$ ./a.out
Enter a single character and press enter: é
String Entered: é: length: 2

Here comes the difficult part, we see that even though we entered a single character, we get the length of the character as 2.

Let’s try the same experiment with a chinese letter 诶
$ ./a.out
Enter a single character and press enter: 诶
String Entered: 诶: length: 3

The result is bizarre, we see that the length is 3.
How can we explain this?

The first thing we should recall is that the size of char is 8 bits or 1 byte. It means it can only carry 256 values. Consider the vast number of languages and dialects in the world, char is not enough to carry the value. So we need a better mechanism called the UTF-8.

As already discussed, I am using UTF-8 in my terminal. So it is able to handle the characters from different languages, but my program is not capable to. Since it is showing very strange answers about the length of the character entered. So we need a better option

Commands: Simple text-based terminal tools

There was a time, long before the ubiquitous windows management on our desktops and desktops, when people used commands to get things done from the computer. These commands were entered on the terminal. There were no beautiful interfaces involved like the menus or the buttons. To see the contents of the directory, they go to the terminal and enter the words ‘ls’ and they see a list of names of files and directories displayed on their terminal with no fancy figures. Similar for every action we now do on the computer, there was an associated command.

Command means to order somebody to do somethings. In the world of computers, there are a fixed number of commands that we give to the computer and the computer can understand these commands. Though there are many research works to make computer understand a large number of commands. But as of 2012, the computers can only understand a limited set of commands.

A command is a software. But normally the word ‘command’ corresponds to the software that run on the terminal. These commands take as input textual information from the user (like the name of a file or an image) and generates textual information as output.

Some commonly used commands in Linux
• ls (to list the contents of a directory)
• cd (change directory)
• pwd (prints current working directory)
• grep (to search for a pattern in a file)

How to Install drupal in localhost

Drupal is one of the best content management software for web site development. But you can install drupal in your local machines and test its working. To see how it works, follow the steps given below.

  • You must have mysql,php and apache installed in your machine.
  • Create a database for drupal usage in mysql
  • Download drupal.
  • If it is a drupal-x.x.tar.gz file, run the following command (Note that x.x corresponds to the version number)
    $ tar -xzf drupal-x.x.tar.gz
  • Rename drupal-x.x to drupal
    $ mv drupal-x.x drupal
  • Now find out the root directory of your Apache. The value will be present in httpd.conf
     DocumentRoot "/usr/local/apache2/htdocs" 
  • Now copy the drupal directory to the Document Root directory
    $ sudo cp -r drupal /usr/local/apache2/htdocs 
  • Now start apache
    $ sudo apachectl start 
  • Enter in your browser the following address “http://localhost/drupal&#8221;
  • If everything is fine, you will see a guided menu to install drupal in your machine.
  • Enter the database name, username and password for the database created.

You may have to change certain file permissions during the installation. Installing drupal locally is very useful for experimenting with drupal features

php-config: How is your php configured?

When you install php, your php is configured based on the packages present in your system at that time or sometimes with default value. To check these values, make use of the php_config. php_config gives all the information regarding how your php is configured.


$ php-config
Usage: /usr/bin/php-config [OPTION]
Options:
 --prefix            [/usr]
 --includes          [-I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib]
 --ldflags           [ -L/usr/lib/mysql]
 --libs              [  -lexslt -liodbc -lmysqlclient -lldap -llber -liconv -liconv -lssl -lcrypto -lcurl -lz -lssl -lcrypto -lm  -lxml2 -lz -licucore -lm -lgssapi_krb5 -lkrb5 -lk5crypto -lcom_err -lcurl -lssl -lcrypto -lz -lxml2 -lz -licucore -lm -lmysqlclient -lz -lm -liodbc -lxml2 -lz -licucore -lm -lxml2 -lz -licucore -lm -lxml2 -lz -licucore -lm -lxml2 -lz -licucore -lm -lxml2 -lz -licucore -lm -lxslt -lxml2 -lz -licucore -lm ]
 --extension-dir     [/usr/lib/php/extensions/no-debug-non-zts-20060613]
 --include-dir       [/usr/include/php]
 --php-binary        [/usr/bin/php]
 --php-sapis         [cli apache2handler]
 --configure-options [--prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --disable-dependency-tracking --with-apxs2=/usr/sbin/apxs --with-ldap=/usr --with-kerberos=/usr --enable-cli --with-zlib-dir=/usr --enable-trans-sid --with-xml --enable-exif --enable-ftp --enable-mbstring --enable-mbregex --enable-dbx --enable-sockets --with-iodbc=/usr --with-curl=/usr --with-config-file-path=/etc --sysconfdir=/private/etc --with-mysql-sock=/var/mysql --with-mysqli=/usr/bin/mysql_config --with-mysql=/usr --with-openssl --with-xmlrpc --with-xsl=/usr --without-pear]
 --version           [5.2.11]
 --vernum            [50211]

As you can see, various useful information like the version, the different library options can be found from this.

How to configure PHP and Apache in Linux and Mac?

You have installed PHP and Apache (Check the installation procedure). But you are facing with the following problems

  • You are not able to configure PHP and apache so that apache can execute the .php files
  • Instead of executing the php files, the browser simply displays the php files like a text
  • Instead of executing the .php files, the browser shows the download option

If you are facing with any of the above problems, it is because the apache needs to load the PHP module. To load the PHP module, you must know the current version of PHP you are running


$ php -v
PHP 5.2.11 (cli) (built: Sep 28 2009 16:48:57)

As you can see, I am using PHP version 5. You may be using version 4 or 5. Next step is to find the libphp5.so or libphp4.so depending on the version you are running. I will continue the remaining post taking into account version 5. You can simply substitute 4 instead of 5 if you are running version 4


$ find / -iname "*libphp*"

/usr/libexec/php/libphp5.so

You may get different path depending on your machine and installation

Now the next step is to stop apache

The apache I have installed is in /usr/local/apache2. So I run the following command


/usr/local/apache2/bin/apachectl stop

Copy the libphp5.so in the modules directory of your apache installation directory (/usr/local/apache2)


sudo cp /usr/libexec/apache2/libphp5.so /usr/local/apache2/modules

Now open httpd.conf. It is present in the conf directory. Add the following lines in /usr/local/apache2/conf/httpd.conf


LoadModule php5_module modules/libphp5.so
DirectoryIndex index.html index.php
AddType application/x-httpd-php php
AddType application/x-httpd-php-source phps

There you are, write a small php file in htdocs directory


$ vim /usr/local/apache2/htdocs/test.php

<?php

echo "PHP is working fine"

?>

And enter the following path in your browser http://localhost/test.php

If everything is fine, you can see the following output


PHP is working fine