Database Reference
In-Depth Information
If you look for the line shown selected in the figure, you will find out which file is causing this
exception to occur, as well as which path and line number the problem is on.
Handling Exceptions
As you might have realized by now, exception handling is a technique you use to avoid any runtime
errors and to handle them gracefully instead of issuing some awkward messages or having the
application hang in front of the user.
Exception handling is mainly based on three keywords:
try
,
catch
, and
finally
. Any program can
have one
try
, followed by one or many
catch
blocks, and then end with one
finally
block.
The
try
block holds any code that is throwing or can throw an exception. The
catch
block serves as a
defensive mechanism and handles the exception that is being thrown. The
finally
block has unique
behavior; it will execute in both situations: when an exception doesn't occur and when it does occur. So,
the best code statements for
finally
are closing file streams, closing database connections, or even
saying good-bye to a customer, and so on, but real-world applications consist of closing streams and
connections instead. I will demonstrate this in the following exercise.
Try It: Adding Exception-Handling Statements
In this exercise, you'll continue to use the created application and then add exception-handling code
blocks to handle such exceptions from being displayed in nonfriendly way to the user.
1. Open the FileHandling project in Visual Studio 2012.
2. Now double-click the Read File button and replace the code with the one in
Listing 11-3.
Listing 11-3.
btnReadFile_Click
StreamReader sr=null;
try
{ sr = new StreamReader(txtFileReadPath.Text);
txtFileContent.Text = sr.ReadToEnd();
}
catch (FileNotFoundException ex)
{
MessageBox.Show(ex.Message + " " + "Please provide valid path and filename");
}
catch (DirectoryNotFoundException ex)
{
MessageBox.Show(ex.Message + " " + "Please provide valid Directory
name", "File Read Error");
}
finally
{
if (sr != null)
{
sr.Close();