Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Hungry Minds - Visual C# Blueprint.pdf
Скачиваний:
101
Добавлен:
12.02.2016
Размер:
9.71 Mб
Скачать

C#

HANDLING EXCEPTIONS WITH THE CATCH BLOCK

You can handle thrown exceptions with a catch block. You can insert a try/catch in all your procedures and just format a message to the user with the error that

occurred. Just formating the current exception into a message will keep your application from terminating, but it will create a frustrated user. To keep a content application user, you want to do more that just display the current error. At a minimum you should trap for common errors and display a custom message that your user can understand.

The granularity of the exception handling determines how polished your final application is and it has a large impact on the usability of the application. Errors happen

in your application, and the way they are handled is key to a good application.

To take exception handling further, you need to handle common exceptions that you know can occur. For example, the sample task below will take you through an example that is doing file access. One of the known issues with file access is attempting to access a file that does not exist. In the case of code that does file access, you want a catch block that explicitly handles the exception generated from a missing file. Inside of that catch block you write code that will collect the relative information about the failed attempt and then log that information and/or pass the information up the call stack while throwing an exception.

HANDLING EXCEPTIONS WITH THE CATCH BLOCK

Á Save the file.

Create a string variable

. and initialize with a text file name.

° Create a string variable to hold a line of text.

· Add a try statement that attempts to open the file and outputs a status message to the console.

Add a while loop to read through the file and output the contents of the file.

Catch blocks can be implemented several ways. Below are several sample catch blocks and a brief explanation of what each one does.

Example:

//Sample 1 – Handles all

//exception, execution continues catch

{

}

Example:

// Sample 2 – Essentially same as 1 catch (Exception e)

{

}

Example:

// Sample 3 - Rethrows exception e catch (Exception e)

{

throw (e);

}

WORKING WITH ERRORS 15

Example:

//Sample 4 – Handles only one

//specific error (all others

//will not be handled)

catch (StackOverflowException e)

{

}

Example:

//Sample 5 – Handles a specific

//error and all others go to the

//general catch statement

catch (StackOverflowException e)

{

}

catch (Exception e)

{

}

Add a catch statement for the

FileNotFoundException and output an appropriate message if the exception was raised.

± Add a catch statement to output exceptions to the console.

¡ Add a debug stop.

Press F5 to save, build, and run the console application.

The FileNotFound Exception is raised and the message for this exception is displayed.

281

C#

USING THE FINALLY BLOCK

ou can run common code that needs to execute after Ya try/catch block by placing the code in an optional

finally block. The finally block is handy for running code that cleans up object reference and any other cleanup code that needs to run after the try and/or catch blocks. The cleanup code in the finally block can be closing a file or a connection to a database.

Finally, blocks will run no matter if an exception occurs or does not occur. You will want to place the finally block after the try and catch blocks. Note that the finally block will always execute, except for unhandled errors like

exceptions outside of the try/catch blocks or a run-time error inside the catch block.

There are cases where you might release or close resources in your try block. If this is the case, you need to validate that this has happened before closing out the resource again. Checking to see if a resource is close is necessary, because you can sometimes generate an exception if you reattempt to close a resource that is already close. To check to see if the resource is already released or not, you can check to see if the object is null ( if (object != null) { object.Close();} ).

USING THE FINALLY BLOCK

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Rename the namespace

Á Save the file.

ExceptionHandling.

 

Create a string variable

 

 

Rename the class name

and initialize with a text file

FinallyBlock.

name.

Add the Main function.

 

° Create a string variable

 

 

to hold a line of text.

· Add a try statement that attempts to open the file and outputs status messages to the console.

Add a while loop to read through the file and output the contents of the file.

WORKING WITH ERRORS 15

Data access code will most likely always be in try/catch/finally blocks. If you compile this sample and run it twice, you will generate a primary key constraint error.

Example:

SqlConnection cnPubs = new SqlConnection(); SqlCommand cmdTitles = new SqlCommand(); try {

cnPubs.ConnectionString = "server=(local);uid=sa;pwd=;database=pubs";

cnPubs.Open(); String sInsertCmd =

"INSERT INTO titles(title_id, title) " + "VALUES(‘BU2222’,’Book Title’)";

cmdTitles.Connection = cnPubs; cmdTitles.CommandText = sInsertCmd; cmdTitles.ExecuteNonQuery(); }

catch (Exception e){ Console.WriteLine

("Exception occurred: \r\n {0}", e);} finally {

cmdTitles.Connection.Close(); Console.WriteLine("Cleanup Code Executed");

Add a catch statement and output a message if the exception was raised.

± Add a finally statement to output messages to the console.

¡ Add a debug stop.

Press F5 to save, build, and run the console application.

The FileNotFound Exception is raised and the message for this exception is displayed, along with several status messages.

283

Соседние файлы в папке c#