Learn to Manage Exceptions in C# Programming

0
1199
C#--0-in-Depth

C#--0-in-Depth

In the previous article, you have gained a basic understanding of exception handling techniques in C#. Now let’s delve deeper into this subject and lets see what more can we get out of it.

When we used the catch statement, we used the generic Exception object. It’s generic because it will catch any exception. You will not be able to know, for example, if the program failed because a file was not found. How can you distinguish this from a failure caused by insufficient file access permissions? For this reason, exceptions are defined in their own namespaces. System.IO.IOException, System.IndexOutOfRangeException, System.NullReferenceException, and System.DivideByZeroException are all examples of C# exception classes. Each class of the exception classes has a descriptive name indicating the type of error it handles.

How to catch multiple exceptions?

It’s possible, and also very common, that you will want to expect several exceptions when you code an application. For example, if you are writing logs to a text file, you want to handle the situation when the file has been accidentally deleted, and also if the file is there, but the process cannot write to it because of some permission issue. C# provides a structured way of handling multiple exceptions; you can add multiple catch statements each handling a specific type. But in order to achieve the desired behavior, you have to order them from the most specific to the most generic. Let’s consider the following example:

Don’t bother yourself now with the System.IO namespace. Just get the idea. The code above is opening a new file called log.txt, then it writes a message to it. Run this code once to create the log.txt file, and ensure that the text message has been successfully written to it (you can find the file by navigating to the directory where you saved your application, then go to bin\Debug folder). Now make this file “read-only” by right clicking on it, choosing “properties” and checking the read-only checkbox. If you try to run this code again, you will have the following output:

Let’s add another more generic exception to our code. But in order to test for unanticipated exceptions, let’s add the following to our code:

The extra step we added was making our program renames the log.txt file to be newlog.txt. Now to test it. But because the method we used cannot overwrite a file that already exists, if you run this code twice the following message will be displayed:

The message appeared because we placed the “Catch-all” exception handling message last in the stack. If we placed it before the UnauthorizedAccess exception, you’d never know why the program was not able to write the message to the file.

Object oriented programming in C#

You’ll often hear people saying C# has been built from the ground up with object oriented paradigm considered. But what is object oriented programming in the first place?

Learn Cloud Computing from Scratch for Beginners

It all starts with an object

If we are talking about mountain climbing then, definitely, there should be a mountain! Similarly the key to understanding OOP is to understand the concept of an object.

An object is a representation of a unit in your code. Throughout the previous articles you have seen how you can create variables, assign values to them and use them in code. Then you learned about functions, which you can use to manipulate those variables. An object can encapsulate both of those in one unit. An object uses properties (variables) and methods (functions) to communicate in code. But what makes an object different from a function in this sense? Well, a lot! This is just the beginning. Objects’ numerous other features make it much more versatile. For example, you can set the visibility level of a member variable (called property henceforth) so that only certain other objects have access to it. The same applies for methods. You can make objects inherit from each other. That is, make a template object with basic properties and methods, and let other objects use this skeleton and add more functionality to it.

But to create an object, there must me some sort of a guideline or a blueprint that defines what this object should be like, what properties and methods it’d contain. This is called a class. When you create an object using a class, you are instantiating it.

Object properties

Properties describe the state of an object. The famous car analogy can shed some light on this: a car is an object. It has tires, a color, and a brand. These are the car’s properties. They describe it. Now a car class will have an integer property for the tires, a string for the brand and another for the color. Those properties may and may not have default values. They will all be available to the object one you instantiate it.

Properties can be read only or they can have read write access. You can also control their accessibility using modifiers like public, private, and protected (covered later).

Object methods

Methods define the behavior of objects. A car can move forward, move backward, and turn right or left. Those motions can be defined in methods like forward(), backward(), right(), and left(). Similar to properties, methods can be protected and using the accessibility modifiers.

The good news is, you’ve been already using objects all along. All the code that wrote since the start of this course was OOP. The main() function is just a method in a class called Program. Any functions that you created were just methods of this class. The dot (.) is used to separate the object instance from it’s property or method. Even the variables you’ve been using like the int and the String are all classes.

From this point forward we are going to explore the rest of the language features in the realm of the object oriented paradigm. You will see how powerful the language can get, and how using objects and classes can make the programmer’s life a lot easier.

Conclusion

In this article, we continued the discussion that started in the previous post about exception handling. You saw how to use multiple levels of controlling errors from the most specific to the least. Then we started viewing C# in its object oriented form. You were introduced to the concept of objects and classes, in addition to properties and methods. You finally discovered that you have already been using classes and objects from the start of the course, although they were used in a procedural form so as to illustrate the basic concepts of the language.

In the next article, we will continue illustrating the aspects of OOP in C# so stay tuned.

LEAVE A REPLY

Please enter your comment!
Please enter your name here