Using the throw keyword 

Sometimes in your own program, you have to create exceptions by yourself. No, not to take revenge on the user, but for the sake of your application. Sometimes, there are situations where you need to throw an exception to bypass a difficulty, to log something, or just redirect the flow of the software. Don't worry: by doing this you are not becoming the bad guy, you are actually the hero who is saving the program from trouble. But how can you create an exception? To do that, C# has a keyword called throw. This keyword will help you to create an instance of a type of exception and throw it. Let me show you an example of the throw keyword:

using System;

namespace ExceptionCode
{
class Program
{
public static void Main(string[] args)
{
try
{
Console.WriteLine("You are the boss!");
throw new DivideByZeroException();
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index out of range " + ex);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Divide by zero " + ex);
}
catch
{
Console.WriteLine("I will catch you exception! You can't hide from me!");
}

Console.WriteLine("See, i told you!");
Console.ReadKey();
}
}
}

The output is as follows:

You can see that, if you run the preceding code, you will get the DivideByZeroException catch block executed.

So, if you want to throw an exception (because you want the upper-layer catch block to handle it, for example), you simply throw a new instance of an exception. This could be any kind of exception, including a system exception or a self-created exception. Just keep in mind that there is a catch block that will handle it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.159.178