Microsoft KB Archive/308345

= How to catch exceptions in Visual C# =

Article ID: 308345

Article Last Modified on 12/11/2006

-

APPLIES TO


 * Microsoft Visual C# 2005
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q308345



For a Microsoft Visual Basic .NET version of this article, see 301283.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.IO
 * System.Security

IN THIS TASK
SUMMARY
 * Requirements
 * How to Catch Exceptions in Visual C# .NET

REFERENCES



SUMMARY
Catching and dealing with exceptions is a standard programming task. This article demonstrates how to use a try-catch-finally block to catch an exception. A try-catch-finally block is a &quot;wrapper&quot; that you put around any code where the possibility of an exception exists.

A try-catch-finally block consists of the following sections:
 * Any code that may throw an exception is placed inside the try block.
 * If an exception is thrown, the catch block is entered, and the program can perform the appropriate operation to recover or alert the user.
 * The code in the finally block is always executed and can perform cleanup after an exception has occurred. The finally block is optional.

back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
 * Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows NT 4.0 Server
 * Microsoft Visual C# .NET or Microsoft Visual C# 2005

back to the top

How to Catch Exceptions in Visual C#
 Create a new Console Application in Visual C#.

Note In Visual C# 2005, Program.cs is created by default instead of Class1.cs.  Replace all of the code in the Class1 code window with the following sample code. The code declares and initializes three variables, wherein the initialization of &quot;k&quot; causes an error. // This code generates an exception. using System;

namespace ExceptionApp {   class Class1 {   static void Main {           Console.WriteLine(&quot;We're going to divide 10 by 0 and see what happens...&quot;) ; Console.WriteLine ; int i = 10 ; int j = 0 ; int k = i/j ; // Error on this line. }   } }                     Press F5. You receive a System.DivideByZeroException exception.  Wrap a try-catch statement around your code to capture the error. The following code catches all errors that are thrown in the code and displays a generic error message. Replace the code in the Class1 code window with the following: // This code shows how to catch an exception. using System;

namespace ExceptionApp {   class Class1 {   static void Main {           try {               Console.WriteLine(&quot;We're going to divide 10 by 0 and see what happens...&quot;) ; Console.WriteLine ; int i = 10 ; int j = 0 ; int k = i/j ; // Error on this line. }           catch {               Console.WriteLine(&quot;An error occurred.&quot;); }   }    } }

 Press CTRL+F5 to run the application. Note that the error message from the catch block is displayed, rather than the system exception message.  If some cleanup or post-processing needs to be done regardless of an error, use the finally part of the try-catch-finally statement. Code in the finally part of the statement is always executed, regardless of an exception. The following code displays &quot;This statement is always printed&quot; in the console, even if no error occurred. Replace the code in the Class1 code window with the following: // This code shows how to catch an exception. using System;

namespace ExceptionApp {   class Class1 {   static void Main {           try {               Console.WriteLine(&quot;We're going to divide 10 by 0 and see what happens...&quot;) ; Console.WriteLine ; int i = 10 ; int j = 0 ; int k = i/j ; // Error on this line. }           catch {               Console.WriteLine(&quot;An error occurred.&quot;); }           finally   //This section is performed regardless of the above processing. {               Console.WriteLine; Console.WriteLine(&quot;This statement is always printed&quot;); }   }    } }                     Press CTRL+F5 to run the project.</li>  You can use the exception object with the catch statement to retrieve details about the exception. An exception has a number of properties that can help you identify the source or even stack information about an exception. This information can be very useful for tracking down the original cause of the exception or providing a better explanation of its source. The following sample catches an exception and gives a specific error message. As before, you can replace the code in the Class1 code window with the following code: // This code shows how to catch an exception. using System;

namespace ExceptionApp {   class Class1 {   static void Main {           try {               Console.WriteLine(&quot;We're going to divide 10 by 0 and see what happens...&quot;) ; Console.WriteLine ; int i = 10 ; int j = 0 ; int k = i/j ; // Error on this line. }           catch(Exception e)            { Console.WriteLine(&quot;An error occurred.&quot;); Console.WriteLine(e.ToString); }           finally   //This section is performed regardless of the above processing. {               Console.WriteLine; Console.WriteLine(&quot;This statement is always printed&quot;); }   }    } } The following code sample demonstrates how to obtain extended error information. This sample provides the message, the source of the error, and the stack trace: // This code shows how to catch an exception. using System;

namespace ExceptionApp {   class Class1 {   static void Main {           try {               Console.WriteLine(&quot;We're going to divide 10 by 0 and see what happens...&quot;) ; Console.WriteLine ; int i = 10 ; int j = 0 ; int k = i/j ; // Error on this line. Control jumps to the catch block. }           //Perform code that deals with the exception or inform the user what occurred. catch(Exception e)             { Console.WriteLine(&quot;The following error occurred:&quot;); Console.WriteLine( e.Message );  // Print the error message. Console.WriteLine( e.Source );   // Name of application or object that caused the error. Console.WriteLine( e.StackTrace ); //String that contains the stack trace for this exception. }           finally   //This section is performed regardless of the above processing. {               Console.WriteLine; Console.WriteLine(&quot;This statement is always printed&quot;); }   }    } }                    </li>  Until this point, you have dealt with the particular case of a non-specific exception. However, if you know in advance what kind of exception is going to occur, you can catch the anticipated exception and process it accordingly. You can then use multiple catch blocks to catch all other exceptions and deal with them as well. The following sample demonstrates this: // This code shows how to catch an exception. using System; using System.IO; using System.Security;

namespace ExceptionApp {   class Class1 {   static void Main {       try {       File.Create(&quot;c:\\temp\\testapp.txt&quot;);  //can fail for number of reasons }       // This error may occur if the temp folder does not exist. catch(IOException ioe) {       Console.WriteLine(&quot;An IO error ocurred. The c:\\temp folder does not exist&quot;); }

// You do not have the appropriate permission to take this action. catch(SecurityException se) {       Console.WriteLine(&quot;You don't have the security permissions to take this action!&quot;); }

// Catch all exceptions. catch(Exception e)         { Console.WriteLine(e.ToString); }   }    } }  Because computer configurations may be different, the sample in this step may or may not throw an exception. If you want to force an IO exception, change the file path to a folder that does not exist on your computer. </li></ol>

back to the top

<div class="references_section">