Using exceptions

As we mentioned previously, errors in C# programs are propagated at runtime using exceptions. When application code encounters an error, it throws an exception, which is then caught by another block of code that collects all the information about the exception and pushes it to the calling method, where the catch block was provided. A dialog box will be displayed by the system if you're using a generic exception handler for any uncaught exceptions.

In the following example, we are trying to parse an empty string into an int variable:

public static void ExceptionTest1()
{
string str = string.Empty;
int parseInt = int.Parse(str);
}

When executed, the runtime throws a format exception with a message stating Input string was not in a correct format. As this exception wasn't caught, we can see the generic handler displaying this error message in a dialog box:

Here are the exception's details:

System.FormatException occurred
HResult=0x80131537
Message=Input string was not in a correct format.
Source=<Cannot evaluate the exception source>
StackTrace:
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Int32.Parse(String s)
at Chapter7.ExceptionSamples.ExceptionTest1() in C:Userssrinisource eposProgramming-in-C-Exam-70-483-MCSD-Guide2Book70483SamplesChapter7ExceptionSamples.cs:line 14
at Chapter7.Program.Main(String[] args) in C:Userssrinisource eposProgramming-in-C-Exam-70-483-MCSD-Guide2Book70483SamplesChapter7Program.cs:line 13

Each catch block defines an exception variable that gives us more information about the exception that is being thrown. The exception class defines multiple properties, all of which hold the following extra information:

Property Description
Data Gets custom-defined details about the exception in a key/value pair collection.
HelpLink Gets or sets a help link related to an exception.
HResult Gets or sets HRESULT, a number value that is associated with the exception.
InnerException Gets the instance of the exception that triggered the exception.
Message Gets detailed information from the exception.
Source Gets or sets the application/instance name or the object/variable that caused the error.
StackTrace Gets a call stack in a string format.
TargetSite Gets the method that triggered the exception.

 

Now, we will try to handle the format exception and see what each property will provide us with. In the following example, we have a try block where the string is being parsed into an integer and a catch block that is being used to catch the format exception. In the catch block, we are displaying all the properties of the exception that we've caught:

public static void ExceptionTest2()
{
string str = string.Empty;
try
{
int parseInt = int.Parse(str);
}
catch (FormatException e)
{
Console.WriteLine($"Exception Data: {e.Data}");
Console.WriteLine($"Exception HelpLink: {e.HelpLink}");
Console.WriteLine($"Exception HResult: {e.HResult}");
Console.WriteLine($"Exception InnerException:
{e.InnerException}");
Console.WriteLine($"Exception Message: {e.Message}");
Console.WriteLine($"Exception Source: {e.Source}");
Console.WriteLine($"Exception TargetSite: {e.TargetSite}");
Console.WriteLine($"Exception StackTrace: {e.StackTrace}");
}
}

We are trying to parse a string into an integer variable. However, this is not allowed, and so the system throws an exception. When we catch the exception, we are displaying each property of the exception to observe what it stores:

Each exception is inherited from the System.Exception base case, which defines the type of exception and details all the properties that provide more information about the exception. When you need to throw an exception, you need to create an instance of the exception class, set all or some of these properties, and throw them using the throw keyword.

You can have more than one catch block for a try block. During execution, when an exception is thrown, a specific catch statement that handles the exception executes first and any other generic catch statements are ignored. Therefore, it is important to organize your catch blocks by placing them in order, that is, from the most specific to the least specific:

public static void ExceptionTest3()
{
string str = string.Empty;
try
{
int parseInt = int.Parse(str);
}
catch (ArgumentException ex)
{
Console.WriteLine("Argument Exception caught");
}
catch (FormatException e)
{
Console.WriteLine("Format Exception caught");

}
catch (Exception ex1)
{
Console.WriteLine("Generic Exception caught");
}
}

When the program executes, although there are multiple catch blocks present, the system identifies an appropriate catch block and consumes the exception. Due to this, you will see a Format Exception caught message in the output:

Format Exception caught
Press any key to exit.

The finally block is checked before invoking a catch block. When using resources in a try-catch block, there is a chance that these resources will move to an ambiguous state and aren't collected until the framework's garbage collector is invoked. Such resources can be cleaned up by the programmer via the use of finally blocks:

public static void ExceptionTest4()
{
string str = string.Empty;
try
{
int parseInt = int.Parse(str);
}
catch (ArgumentException ex)
{
Console.WriteLine("Argument Exception caught");
}
catch (FormatException e)
{
Console.WriteLine("Format Exception caught");

}
catch (Exception ex1)
{
Console.WriteLine("Generic Exception caught");
}
finally
{
Console.WriteLine("Finally block executed");
}
}

As you can see, the finally block was executed, but not before an exception was raised and caught using the respective catch block:

Format Exception caught
Finally block executed
Press any key to exit.

Although we had three different catch blocks, the format exception was executed and the finally block was executed after.

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

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