Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Exceptions in Csharp

In this tutorial, we are going to see how we can handle exception in C# with care, chain exceptions, etc. In addition, I will talk about how you can code your own exceptions for them who wish to do so in their projects.

Introduction

Almost all modern programing languages provide methods to handle exceptions. Unexpected situations can occur while running a program, such as: trying to access a file that does not exist, or dividing a number by zero and so on. In this tutorial, we are going to see how we can handle exception with care, chain exceptions,etc.

In addition, I will talk about how you can code your own exceptions for them who wish to do so in their projects.

How does it work in dotnet programming?

Comment from Microsoft:

Exceptions have the following properties:

  • When your application encounters an exceptional circumstance, such as a division by zero or low memory warning, an exception is generated.
  • Use a try block around the statements that might throw exceptions.
  • Once an exception occurs within the try block, the flow of control immediately jumps to an associated exception handler, if one is present.
  • If no exception handler for a given exception is present, the program stops executing with an error message.
  • If a catch block defines an exception variable, you can use it to get more information on the type of exception that occurred.
  • Actions that may result in an exception are executed with the try keyword.
  • An exception handler is a block of code that is executed when an exception occurs. In C#, the catch keyword is used to define an exception handler.
  • Exceptions can be explicitly generated by a program using the throw keyword.
  • Exception objects contain detailed information about the error, including the state of the call stack and a text description of the error.
  • Code in a finally block is executed even if an exception is thrown, thus allowing a program to release resources.

Let’s go back to MrBool

Consider this case: you wish to write a method that helps you to divide a number by another and then return the result. These two numbers are unknown; one of them can be zero, and as you know well rather than me, dividing a number by zero returns the infinite. The infinite is an exception: you may handle it in dotnet like this:

staticintSafeDivision(int x, int y)
{
int result=0;
try
    {
result=(x / y);
    }
catch
	{
System.Console.WriteLine("Can’t divide by zero!");
}
return result ;
}

In this method, we try to dividex by y and we will catch an exception if any.

In the try clause, you write codes that can generate an exception. Then you handle this (or these) exception(s) within catch clause.

Run the following program and you will get the result bellow (figure 1).

namespaceExceptionsCSharp
{
classProgram
    {
staticvoid Main(string[] args)
{
System.Console.WriteLine(SafeDivision(6,2));
System.Console.WriteLine(SafeDivision(3, 0));
System.Console.ReadKey();
        }
staticintSafeDivision(int x, int y)
        {
int result ;
try
            {
result = (x / y);
            }
catch
            {
System.Console.WriteLine("Can’t divide by zero! I return 0 instead");
result = 0;
            }
return result;
}

    }
}
Result of the code above

Figure 1: Result of the code above

Knowing what is the exception that occurred?

It´s also possible to know information about an exception within the catch clause. You have to pass the exception type as a parameter as follows

Exception Example

Figure 2: Exception Example

What does this mean?

Each exception inherits from the System.Exception class, provided by Miscrosoft .Net framework! This class has methods and properties that allow you to know more about a given exception. Here are some most used properties and methods within the Exception class:

CONSTRUCTORS

The dotnet Exception class has four constructors, let me explain you their roles:

  • The first is an empty constructor: Initialize a new instance of System.Exception, let’s forget it!
  • The second is supposed to accept a string as parameter. This string is a message that will describe the exception, elsewhere it’s caught.
  • The other constructor accepts a string to describe the exception, and a reference to the innerinstanceof System.Exceptionthat caused the current exception.
  • The last constructor initializes a new instance of the System.Exception class with serialized data.

PROPERTIES

  • HelpLink : This property helps you to get or sets a link to the help file associated with the exception. You can set this value to http://www.mysite.com/help?e=123 for example
  • InnerExceptionGets the System.Exception instance that caused the current exception.
  • Message:This property gets a message that describes the current exception.
  • Source:Gets or sets the name of the application or the object that causes the error.
  • StackTrace:this property is a string representation of the immediate frames on the call stack.
  • TargetSite:Gets the method that throws the current exception.
  • Data :Gets a collection of key/value pairs that provide additional user-defined information about the exception. We are not going to talk about this property in this tutorial. Please visit the msdn website

Catch and then catch again

In C# dotnet, you can chain catch clause in order to catch all exceptions that can be thrown.

Consider the case that your program has many instructions that can throw many exceptions. You may wish to handle each of these exceptions separately. To do so, proceed as follows

using System;

namespaceExceptionsCSharp
{
classMyException:Exception
    {
staticvoid Main() {
Console.WriteLine("Handling many exceptions");
try {
int x = 2, y=0;
string s = "Hello!";
                y = int.Parse(s); //thows Format Exception
                x = x / y; //thows divide by zero exception
            }
catch (DivideByZeroException ex1)
            {
//handles DivideByZeroException
Console.WriteLine("Divide by Zero exception thrown!");
            }
catch (FormatException ex2)
            {
//Handles Format Exception
Console.WriteLine("Format Exception thrown!");
            }
catch (Exception ex) {
//Handles any other unhandled exception
Console.WriteLine("Exception occured "+ex.Message);
            }
Console.ReadKey();
        }
    }
}

In this code, the try code bloc has two instructions that can throw two different exceptions:

The first code int.Parse(s); tries to parse a string named s, in order to get its integer value. As you can see it, s has a value “hello!” which is not a good integer format. So, this code block will throw a FormatException according to the dotnet policy.

The second code bloc is x=x/y. This will throw a Divide by zero exception if y=0.

Given these two blocs of code, we had to handle them within two chained catch clauses. The last catchclause is to handle all other unpredictable exceptions.

Caution with chained catch clauses

Note that only one catch clause is executed! Even if the try clause throws many exceptions, only the first clause which corresponds well to the thrown exception will be called. All other catch clauses are ignored.

While handling many exceptions, you must respect the hierarchy of exception classes. YOU CAN’T PUT A CATCH CLAUSE IF A PREVIOUS CATCH CLAUSE ALREADY CATCHES ALL EXCEPTIONS OF THIS OR OF A SUPER TYPE

Please don’t try the following code at home!

try {
int x=6,y=0 ;
x=x/y ; //DivideByZero
            }
catch (Exception ex) {
//THIS WILL NOT WORK
Console.WriteLine("Exception occured "+ex.Message);
            }
catch (DivideByZeroException ex1)
            {
//handles DivideByZeroException
Console.WriteLine("Divide by Zero exception thrown!");
}

This will never work since the DivideByZeroException class inherits from the Exception class. The scenario is that, the divide by zero exceptionis of type of Exception and before itwould be thrown, the base exception already is!

So, what Finally?

Now you come through the point where you haveto decide what to do if an exception is thrown or not! Use the finally clause to manage it as follows

using System;

namespaceExceptionsCSharp
{
classFinallyClause
    {
staticvoid Main() {
try
            {
thrownewException("Trying to throw it anonymously!");
            }
catch (Exception ex)
            {
Console.WriteLine("Exception occured");
            }
finally {
Console.WriteLine("Finally don't care if an exception occured or not!!!");
            }
Console.ReadKey();
        }
    }
}

Result

Figure 3: Result

This result shows two lines of text: the first says that one exception occurred while the shows how the finally clause will always be executed even if the exception has been thrown or not.

Before leave, let’s see how we can code our own exceptions.

Creating, throwing and Handling your own exceptions

Creatingyour own exceptions

For one reason or another, you may wish to define your own exception, if .net does not provide a suitable exception class.

In this case, you have to be good with OOP (object oriented programing), this because you will have to inherit you exception class from the dotnet exception base class.

When writing you exception class, you must avoid overriding the base class properties and methods. This assumes that you can’t have a property named Message in your child class, because it can cause unexpected result.

Here is a skeleton of a custom exception class

publicclassMyException : System.Exception {
//class fieldshidden
    }

You can wish to describe an exception of type MyException. To do this, you can writeits constructor as follows:

publicclassMyException : System.Exception {
publicMyException(string description):base(description) {
        }
    }

Note: this is not the unique way to do it!

The MyException constructor calls the base class constructor, in order to initialize the current exception with the given description.

You can also add methods and properties to this class, in order to call them upon an instance of MyException type.

Throwing(your) exceptions

To throw or handle an exception, do the same as dotnet exception, according to what is said in this tutorial. You can use

throw new MyException(“My Exception was thrown anonymously”);

Handling (your) exceptions

To handle an exception of type MyException for example, Or use the code bellow to handl a MyException exception

try
            {
thrownewException("Trying to throw it anonymously!");
}
catch (MyExceptionex)
            {
Console.WriteLine("Exception occurred "+ex.Message);
            }
finally {
Console.WriteLine("Finally don't care if an exception occured or not!!!");
}
Console.ReadKey();

Thank you for following this tutorial. I wanted to share something with you, about the ability to handle exceptions within a c# program. We’ve learnt chained catch clauses, which is not supported in many other languages, such as the old java which does it otherwise…

Have a question? Ask it by email or write a comment. I will be glad to answer you.

See you next!



Web Developer at CYBERNET sprl.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login