Search:

Custom Search
_________________________________________________________________

Saturday, August 30, 2008

Understanding Exceptions provided by the .NET Framework - Part 2.

You may saw in the previous post, a couple of exceptions we can use that are provided by the .Net Framework derived from the System.Exception class. Those two exceptions were: The StackOverflowException and the NullReferenceException.
Now I will describe to you the OutOfMemoryException and the DivideByZeroException.

The OutOfMemoryException

This exception is thrown by the CLR when your machine runs out of memory. Every time you create an object using new, some memory will be reserved for it. In case there is now enough memory, the exception will be triggered.
Let´s write an example now. Supose you want to create a Hashtable that allocated a large capacity. If there is no memory to do this, the CLR throws the exception.
Take a look at this C# example:

using System;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

namespace ConsoleApplication5

{

class Program

{

static void Main(string[] args)

{

try

{

Hashtable hatb = new Hashtable(91230000);

}

catch (OutOfMemoryException)

{

Console.WriteLine("CLR out of memory");

}

}

}

}


Console:



The DivideByZeroException

This exception is quite simple: when you are dividing by 0, the CLR throws this exception.
Take a look at this example:

class Program

{

static void Main(string[] args)

{

int a = 5;

int b = 0;

try {

int res = a / b;

}

catch(DivideByZeroException){

Console.WriteLine("You are dividing by 0");

}

}

}



Console:

1 comment:

Maria Mcclain said...

hi CoderG, nice post & good blog, i think u must try this site to increase traffic. have a nice day & keep blogging!!!