Home > C#, Learn C# > Learn C# – Handling Exceptions – Part 1

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.

Advertisements
Categories: C#, Learn C# Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: