Learn C# – Handling Exceptions (4) – Custom Exceptions

  1. Handling Exceptions – Part 1 – Basic Try / Catch
  2. Handling Exceptions – Part 2 – Catch block
  3. Handling Exceptions – Part 3 – Throwing Exceptions
  4. Handling Exceptions – Part 4 – Custom Exceptions

We met some common exception classes till now, and we even experienced throwing those exceptions by ourselves. That’s not always the case – we might want from time to time to throw our own exceptions, that will describe our own errors. For that purpose we should take a look first in the Exception class.

The Exception class

The basic Exception class is very simple, and contains some important properties:

  • Message – Contains details about the thrown exception.
  • Stack Trace – Contains details about all the methods involved.
  • InnerException – Sometimes contains details about the encapsulated exception.

There are some others, but those are the most useful. The constructor of the Exception class can accept custom message, so we can use that in order to supply our own exception:

void RegisterStudent(int age)
{
if (age < 18)
throw new Exception("Student can't be younger than 18 years old!");
}

This solution can feet our needs, but we usually don’t want to rely on strings to distinguish between exceptions. We will prefer something more strongly typed.

Custom Exceptions

The second solution for our desire will be to create custom exceptions. Custom exceptions are very simple to create, and it has only one rule: Inherit the base Exception class (or one of its childs). You can add whatever properties you want to your custom exception class, and use whatever constructor you’d like in the base class. Sometimes you won’t add any property at all – by creating specific type to describe the exception it might be enough. Let’s declare one:

public class StudentAgeException:Exception
{
public StudentAgeException(int age)
:base ("Age "+ age+" is not allowed. student age should be at least 18 years old")
{

}
}

And now we’ll use it:

void RegisterStudent(int age)
{
if (age < 18)
throw new StudentAgeException(age);
}

In the above example we declare new custom exception, that accept int parameter in its constructor and pass a message to the base constructor describing the issue. Whoever get’s the exception don’t need to rely on the message to understand the problem, since the problem is also identified by the type of the exception itself. That way is much more strongly typed and safe, since the caller can now create specific catch block to catch only StudentAgeException, and handle this exception in more specific way.

In the Next post we’ll describe the finally block, which will be the last part of our series.

Learn C# – Handling Exceptions(3) – Throwing Exceptions

  1. Handling Exceptions – Part 1 – Basic Try / Catch
  2. Handling Exceptions – Part 2 – Catch block
  3. Handling Exceptions – Part 3 – Throwing Exceptions
  4. Handling Exceptions – Part 4 – Custom Exceptions

Untill now we saw many examples where unprotected code can lead to exceptions. Those exceptions was thrown by the CLR in a result of some wrong input or action. Let’s try to control a little bit more on the process of throwing the exceptions – not only the CLR can do it!

Throwing an exception means “let others know that something wrong happen”. The syntax is pretty simple as well: just use throw, like this:

void Divide (int x, int y)
{
if (y == 0)
throw new ArgumentException();
}

But what we’re throwing? Actually that’s pretty simple too: we must throw an instance of some exception class. In the above example, we’re throwing a new instance of the ArgumentException class, that inherit the base Exception class. Of course, we can also write the same code like this:

void Divide (int x, int y)
{
if (y == 0)
    {
      ArgumentException ex = new ArgumentException();
      throw ex;
    }
}

At this stage I don’t really care who’s handle the exception. I just want to “clear my table” and make sure that I’ve published my problem well. The person who call the code, and in that case – the method caller, should be responsible to handle any exception properly.

One word about bubbeling

A very important behavior of exceptions: from the moment exception was thrown, he only looks for handler. As soon as he will find one everything will come to his place. But, as long as the exception couldn’t find any relevant handler (catch block) – he will keep look for one direction up. Means that if the exception was thrown outside try block, the exception will look for handler in the method caller, and in his caller, and so on untill he gets to the operating system, means crashing.

Throw inside catch block

Sometimes even though we already caught the exception, we will want to throw it again, since we need to handle it again on another place. We can throw the same exception from the catch block, or throw new one.

try
{
  int x = 0;
  int y = 10 / x;
  Console.WriteLine("Done");
}
catch (DivideByZeroException ex)
{
  Console.WriteLine("Error!!");
  throw;//throws the same exception.
  //another version for this will be "throw ex;"
}
try
{
  int x = 0;
  int y = 10 / x;
  Console.WriteLine("Done");
}
catch (DivideByZeroException ex)
{
  Console.WriteLine("Error!!");
  throw new Exception(); // look for another handler
}

In the next post we’ll look more closely into the Exception class, and try create one of ourselves.

Categories: C#

Learn C# – Handling Exceptions – Part 2

  1. Handling Exceptions – Part 1 – Basic Try / Catch
  2. Handling Exceptions – Part 2 – Catch block
  3. Learn C# – Exceptions Handling – Part 3 – Throwing Exceptions

In this part we goanna look in more depth in the try/catch clauses.

The simple case of try/catch, as we seen in the last post, can catch any exception occurred in the try block, and let us handle it in our catch block.

try
{
  int x = 0;
  int y = 10 / x;
  Console.WriteLine("Done");
}
catch
{
  Console.WriteLine("Error!!");
}
//OUTPUT:Error!!
//Notice: "Done" wasn't printed to the console, since the exception was thrown before.

Let’s see some other options available for the try / catch.

Exception details

Not only the catch block can catch our exceptions, but also supply details about the caught exception, like this:

try
{
  //some exception
}
catch (Exception ex)
{
  //ex is an instance of the Exception class, with properties that supply many details about the exception.
}

The Exception class is the base class for any exception used in the .NET framework, and will be described in details later. For now, just note that this class contains some properties with details about the exception, as error message, where the exception originally occurred, etc.

Handle specific exception

The Exception class is not the only class in .NET used to handle exceptions. Lot’s of other classes are used, and all share one important behavior: They all inherit (directly or indirectly) from the base Exception class. NullReferenceException, DivideByZeroException and many others are all classes that have the same goal – handling exceptions. the difference between them is only the exception type, and sometimes, the details supplied.

specifying specific exception class in the brackets after the catch keyword will result catching only exceptions from this specific type. catch block without any type defined – will catch any exception. For example:

try
{
  int x = 0;
  int y = 10 / x;
}
catch (DivideByZeroException ex)
{
  Console.WriteLine("Error!!");
}
//OUTPUT:Error!!

In the above example, any other exception do not get caught (and if the program won’t find any suitable exception handler – it will probably crash). Notice that unlike method parameters, the ex used as a parameter name for the DivideByZeroException instance is not mandatory, and if you not going to use the ex properties, but only want to limit the exception types been caught, you don’t need to declare ex.

Handling some specific exceptions

The above technique of handling one specific exception, can be multiplied to more than one specific exception, like this:

try
{
 int x = int.Parse(Console.ReadLine());
 int y = 10 / x;
}
catch (DivideByZeroException ex)
{
 Console.WriteLine("Divide by zero exception was caught");
}
catch (FormatException ex)
{
 Console.WriteLine("Format exception was caught");
}

Now we handle two different exceptions – one for the DivideByZero and other for the Format. Whichever occurs first will cause his own catch clause to be executed.

One important thing need to be taken in consideration when declaring multiple exception handlers – The order of the catch clauses. Let’s have a look in some example:

try
{
 int x = int.Parse(Console.ReadLine());
 int y = 10 / x;
}
catch (Exception ex)
{
 Console.WriteLine("Divide by zero exception was caught");
}
catch (FormatException ex)
{
 Console.WriteLine("Format exception was caught");
}

This Example will cause compile-time error. The first catch declares the base Exception class as the type, and the second one declare the FormatException. Since all exception inherit from the base Exception class, any exception that will be thrown in the try block will be considered to be general Exception, so it will be caught in the first catch. Hence, the second catch block will never be called.

In the next post we’ll try to throw some exception by ourselves!

Categories: C#, Learn C# Tags: , , , ,

Learn C# – Handling Exceptions – Part 1

  1. Handling Exceptions – Part 1
  2. Handling Exceptions – Part 2

Let’s start with three basic assumptions:

  1. Developers usually don’t think about all possibilities.
  2. Users are not always friendly.
  3. A good program should handle any situation.

And that brings us to our subject: Handling exceptions.

Exception is any problem that the application hasn’t learned to deal with. Wrong input from the user can cause exception, as well as wrong mathematical operation, or sometimes the inability to connect to the internet when network is down. Since every application need to know exactly what to do anytime – when it doesn’t / can’t – exception been thrown.

Here are some examples:

int myNumber = int.Parse(Console.ReadLine());
//This code can optionally throw exception, if the user input can't be parsed to integer.

 

int x = 0;
int y = 10 / x;
//this code will throw exception anyway, because dividing by zero is not allowed!

 

File.Delete("some path to non-exist file");

Exceptions aren’t bad things by themselves, but if we won’t handle them carefully, they may crash our program, and we don’t want this to happen, right?

In order to handle exception we can use the try/catch clauses, like this:

try
{
  //here is block of code that potentially can throw exception
}
catch
{
  //if exception will be thrown above, this code will be excuted
}

Any exception that will be thrown in the “try” block, will cause immediate transition to the “catch” block. The rest of the code in the try block that hasn’t been executed yet – won’t be executed anymore. here is an example:

try
{
  int x = 0;
  int y = 10 / x;
  Console.WriteLine("Done");
}
catch
{
  Console.WriteLine("Error!!");
}
//OUTPUT:Error!!
//Notice: "Done" wasn't printed to the console, since the exception was thrown before.

In the next posts we goanna cover exception handling in more depth.

Categories: C#, Learn C# Tags: , , , ,

Learn C# – If statement – Part 2

In the last post we discussed about simple if statements and boolean expressions.

Now, what if we want to check if some expression is equals to false? the simple way will be this:


bool b = true;

if (b == false)

{

//code will get executed only if b equlas to false.

}

Of course, our boolean expression won’t be like this always,  so we can also use this one:


int i=10;

if (i != 10)

{

//code will get executed only if i not equal to 10

}

As you can see, the operator “!=” means “not equal to”. Another relevant operator for this kind of  statements will be the “!” operator, which means NOT, take a look:


bool b = false;

if (!b)

{

//code here will get executed since b equal to false, and that's what we've looked for in the condition

}

int i = 3;

if (! (i==3))

{

//code here won't get executed since we're looking for "Not (i equal to 3)".

}

 In the next post will see how to take an alternative actions, if the condition does not exist.
Categories: C#, Learn C# Tags: , , ,

Learn C# – If statement – Part 1

Introduction

Frequently when writing code, we need to perform specific code section only if certain condition exist.

For example, we want to call the student’s mother only if he failed the exam, or printing receipt to the client only if the payment was approved by the credit card company. Taking actions according to conditions is a very common thing to do in real life, and in particular while coding.

Boolean expressions

Here is another thing that we do all the time without realizing it – Asking ourselves questions. Every day, every hour, and probably more than once at an hour. In order to take actions under conditions we must first define the question – and more important  – find the answer – Yes or No. Questions with only Yes No answers are called boolean  statements. Lets take a look at several different boolean expressions:


bool b = true;

OK, that’s not really a boolean expression, it’s more like variable declaration and assignment. But, if you take a look more closely, you’ll be able to see that the variable “b”, after the assignment, is a boolean expression by himself. That’s because it fits into the “Answer” rule – Everything that gives us Yes or No answer (even if there is no question around) will be considered as boolean expression. Since the value of  “b” is “true”, we can consider it as a boolean expression. Let’s see some more examples:


a == 5

Assuming “a” is an integer variable, we’re using the “==” operator to ask our question:  Is “a” equal to 5. I don’t really know at the moment what is the value of  “a”, but I do know that this question has only one of two answers: Yes or No. Here are some more examples for boolean expressions, before we leap into the “if” river:


//x is an integer
x > 10
//str is a string variable
str == "my string"

We’ll talk more about operators in a different post.

If Statement

After we understood some basic things regarding boolean expressions, all we need to do is to push it into the “if” statement using the following syntax:

if ( /* condition */ )
{
   //do something
}

or more specifically:

if (a == 5)
{
   Console.WriteLine("a is Equal to 5!")
}

Notice, that the code written inside the braces will only get executed if the boolean expression of the if statement will be equal to true. Otherwise, the program will continue to execute the code right after the braces. Of course, we can execute more than one line of code inside the braces – as long as we didn’t close the braces – we can proceed with writing a code that only get executed if the boolean expression of the if statement will be true. If we only want to execute one line of code – we can avoid the braces and write this code right after the if statement, like this:

if (a == 5)
   Console.WriteLine("a is Equal to 5!")
Console.WriteLine("This line will be executed anyway!!!")

Notice that the second Console.WriteLine() will get executed anyway even if the condition inside the if will be equal to false – since “if” without braces will only affect the first line of code.

One more thing for this post – We took an example from an integer variable. Let’s take a look in a boolean variable:

bool b = true;
if (b == true)
{
   Console.WriteLine("b is Equal to true!")
}

Since the boolean variable was assigned to true, the condition exist and the Console.WriteLine line will get executed. However, as we said before, the variable “b” itself is a boolean expression (since it’s a boolean variable), so we don’t need to actually ask the question in it’s full form. We can just use this code:

bool b = true;
 if (b)
 {
 Console.WriteLine("b is Equal to true!")
}

Pay attention to the slight difference between those 2 versions, They are both true, and you can use them both, But it definitely gives you some idea about using boolean expressions inside if statements.

We’ll continue with the “if” statements in the next posts.

Categories: C#, Learn C# Tags: , , ,

Reading leading Zeros from Text files with OLEDB

OLEDB allows us to read large text files, exactly like reading tables from DataBase. For example, using this connection string, you can simply create connection to CSV file:

@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=""[Your Directory]"";Extended Properties=""text;HDR=No;FMT=Delimited"";

and then reading it with this command:

"SELECT * FROM [FileName]"

Not only .csv files applicable with this Format, you can also set the delimiter to other values, as Tab.

Suppose you have this simple .csv file:

ColumnA,ColumnB,ColumnC
0001,12,13
00002,15,16

When reading this file to DataTable using OleDbDataAdapter, the leading zeros for the first column will be omitted, since the DataTable recognize this column as an Integer column, and there is no meaning for leading zeros. In order to tell the DataTable to treat this column as a string column, just add file called schema.ini in the same directory of your .csv file, with the following content:

[YourFileName.csv]
ColumnA= Text
ColumnB=Integer
ColumnC=Integer

Now the DataTable will read the first column as string. More options for the schema.ini file you can find here: Much ADO About Text Files

Categories: ADO.NET, C# Tags: , ,
%d bloggers like this: