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.
Comment from Microsoft:
Exceptions have the following properties:
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;
}
}
}

Figure 1: Result of the code above
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

Figure 2: Exception Example
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:
The dotnet Exception class has four constructors, let me explain you their roles:
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.
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
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!
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();
}
}
}

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.
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.
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”);
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!
See the prices for this post in Mr.Bool Credits System below: