Monday, December 03, 2012

coding lesson: error codes

So  I was expecting to be posting a lesson on how to make a server program that listens for a connection and then responds to a connection by sending a message to the client.

But in order to reduce the amount of code in that program first I'm going to introduce a way or outputting errors.

A program could fail in a few ways, I guess out of memory etc, but it can be difficult to trap those errors in a program, what's more the system knows what the error is, like I can't open a listening port because the port is already in use.

So to trap these errors and report useful information we use a call to a function found in a standard header file:

The standard header is stdlib.h that is included in the same way as stdio.h

then we are able to call a function called perror, tell it how we want to message to start, then the function will add what the system knows the error as, and print that to the screen.


#include <stdio.h>
#include <stdlib.h>
int main()
{
    perror("error_one");

printf(\r\n"program running");
        return 0;
}


when this program runs it prints the error message (no error) then prints a message to say that the program is still running.

Some errors are going to mean that we just can't go on. For example in the
creation of a server program that's going to listen on a network socket, if you can't create a socket, then the program is pretty useless and should terminate.

#include <stdio.h>
#include <stdlib.h>

void error(const char *msg)
{
    perror(msg);
    exit(1);
}
int main()
{

    perror("error_one");
    printf(\r\n"program running");
    error("error_two");
    printf(\r\n"program running");
    return 0;
}



When this is run you can see that the message program running is only displayed once.

That's because when we call error there is a function called exit.

This does exactly what it says on the tin...

we can now call perror for non fatal errors saying hey you might want to fix this, any fatal errors now we can let the user know what's wrong and exist the program in a good way


No comments: