Click here to Skip to main content
Click here to Skip to main content

If/else instead of try/catch

By , 9 Nov 2012
Rate this:
Please Sign up or sign in to vote.

Introduction

In this tip I tell you how to use if/else instead of try/catch.

Try/catch

To handle exceptions, the try/catch block is very helpful in C#:

try
{
    // code to try
} 
catch (Exception e)
{
   // catch an exception
}

There're a few exceptions that we can prevent with an if/else statement.

Preventing exceptions with if/else

IndexOutOfRangeException

One of the exceptions that we can prevent with an if/else statement, is the IndexOutOfRangeException.
Instead of this:

int[] array = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int j = Convert.ToInt32(Console.ReadLine());
try
{
   int i = array[j]; // this can throw an error
}
catch (IndexOutOfRangeException)
{
   Console.WriteLine("Index out of range");
}

You can do this:

int[] array = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int j = Convert.ToInt32(Console.ReadLine());
if (array.Length > j && j > -1)
{
     int i = array[j]; // now, this can't throw an error
}
else
{
     Console.WriteLine("Index out of range");
}

NullReferenceException

Another exception is the NullReferenceException. With an if statement, you can check for null.

string str = null;
if (str != null)
{
    str.Replace("a","b"); // this can't throw an error
}
else
{
    Console.WriteLine("str is null!");
}

DivideByZeroException

An DivideByZeroException throws when you try to divide a number by zero. That's also an exception that we can prevent with if/else:

int _int1 = Convert.ToInt32(Console.ReadLine());
int _int2 = Convert.ToInt32(Console.ReadLine());
int result = 0;
if (_int2 != 0)
{
     result = _int1 / _int2;
}
else
{
   Console.WriteLine("Can't divide by zero!");
}

ObjectDisposedException

You can't check whether a object is disposed or not, but the Control class in Windows Forms has a IsDisposed property that you can use. 

Control c = new Control();
c.Dispose();
if (!c.IsDisposed)
{
   c.Controls.Add(new Control());
}
else
{
   MessageBox.Show("Control is disposed!");
}

FileNotFoundException

The FileNotFoundException is also an exception that you can prevent with if/else.

string filename = Console.ReadLine();
if (System.IO.File.Exists(filename))
{
    string content = File.ReadAllText(filename);
}
else
{
    Console.WriteLine("File not found.");
}

Why if/else and not try/catch?

Speed 

If you've one if/else block instead of one try/catch block, and if an exceptions throws in the try/catch block, then the if/else block is faster (if/else block: around 0.0012 milliseconds, try/catch block: around 0.6664 milliseconds). If no exception is thrown with a try/catch block, then a try/catch block is faster. But if you use 100 try/catch blocks in your program, and if one exceptions throws, then 100 if/else blocks is faster.

Skipping immediately

If you've a try/catch block where you divide by zero, and you do a few things before you divide, then some useless code is running. If you've a if/else block, then all useless code is skipped immediately, then you don't need to wait until the division.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

ProgramFOX

Belgium Belgium
No Biography provided

Comments and Discussions

 
Questionstring null checking PinmemberSpiff Dog7-Nov-12 9:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 9 Nov 2012
Article Copyright 2012 by ProgramFOX
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid