System ProgrammingLearn about Error handling in C# Programming

Learn about Error handling in C# Programming

Error handling refers to the methods and techniques that a programmer uses to anticipate and work with errors that might happen during application execution.

What is an exception?

An exception is “something wrong” that happened during code execution. That is, at runtime. Trying to write to a read-only file, dividing a number by zero, and using a network port that is already in use are all examples to exceptions that may occur while a program is running.

Handling exceptions involved writing code that is ready to manage them, perhaps by printing a friendly message to the user informing him/her with what happened, and whether or not an action can be taken from the user’s side to correct it.

Sometimes, however, you may want to raise your own exceptions. In other words, you want the program to consider a legitimate event as an error. To see an example, recall the program we wrote in the previous article:

class Program
    {
        public delegate string FormatterDelegate(string s);

        static string hyperlink(string str) 
        {
            return "<a href='" + str + "'>" + str + "</a>";
        }

        static string paragraph(string str)
        {
            return "<p>" + str + "</p>";
        }

        static string format(string s, FormatterDelegate formatter)
        {
            return "The link is: " + formatter(s);
        }

        static void Main(string[] args)
        {
            FormatterDelegate hl = new FormatterDelegate(hyperlink);
            FormatterDelegate p = new FormatterDelegate(paragraph);
            string link = format("www.google.com",hyperlink);
            string text = format("www.google.com", paragraph);
            Console.WriteLine(link);
            Console.WriteLine(text);
            Console.ReadLine();
        }
    }

It accepts a string and outputs it as a hyperlink. But what if the passed string was just “google” instead of “www.google.com”? In such a case, the hyperlink will not work, as it will direct the user to an invalid website. But C# doesn’t care as long as the passed argument is, technically, a string.  You could raise an exception here complaining that the input string should be in a specific format.

Exception handling is done by placing the code to be managed inside try..catch..finally block. The try contains the code block just as it is without any changes. Then the catch statement is followed by an Exception object (more on that later). This object contains useful properties, including the message, which holds the friendly text that describes why the failure happened. The final statement is optional. It contains any code that must run after the exception handling is complete, whether an error was handled or not. It’s like a cleanup block that may, for example, close any database connections or open files.

Learn Cloud Computing from Scratch for Beginners

Let’s rewrite the above code so that it accepts the URL from the user instead of hard coding it, and raises an error if the string is does not start with www. or does not end in .com:

class Program
{
public delegate string FormatterDelegate(string s);

        static string hyperlink(string str) 
        {
            return "<a href='" + str + "'>" + str + "</a>";
        }

        static string paragraph(string str)
        {
            return "<p>" + str + "</p>";
        }

        static string format(string s, FormatterDelegate formatter)
        {
            if (!s.StartsWith("www.") || !s.EndsWith(".com"))
            {
             throw new Exception("Please enter a string that starts with www and ends with .com");
            }
            return "The link is: " + formatter(s);
        }

        static void Main(string[] args)
        {
            FormatterDelegate hl = new FormatterDelegate(hyperlink);
            FormatterDelegate p = new FormatterDelegate(paragraph);
            Console.WriteLine("Please enter the URL to be formatted: ");
            string url = Console.ReadLine();
            try
            {
                string link = format(url,hyperlink);
                string text = format(url, paragraph);
                Console.WriteLine(link);
                Console.WriteLine(text);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
            Console.ReadLine();
        }
    }

We added a condition to the format function that will check the entered string. If it does not start with “www.”, or does not end in “.com”, it will throw a new exception object. The object constructor (more on objects and object oriented programming later) accepts a string that will be used as the message property of the object. Then we place the code inside try and catch blocks. An exception object must be passed to the catch keyword. This object is available to you throughout the catch block. In our example, you just print the friendly message to the screen informing the user of the appropriate way to enter a URL string. If you run this code, the output should be similar to the following:

Please enter the URL to be formatted:
google
Please enter a string that starts with www and ends with .com

Needless to say that, thanks to the delegate we created, we didn’t have to place the exception-throwing code in each function that formats the URL.

Obviously, this is not the most accurate way to evaluate URL’s as a valid link may not start in www, and of course it may end in .net or .org or other tld’s but you get the idea.

Conclusion

In this article, we have scratched the surface of exception handling in C#. You have studied what exceptions are, how they can be used to control code execution, and how to create your very own exceptions to protect your code from invalid inputs.

In the next article, you will see more details about the other types of exceptions, and how to configure them. Then we will start our exciting discussion of object oriented programming, which is the heart and soul of C#. Stay tuned.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -