How to: Use the Try/Catch Block to Catch Exceptions
Microsoft Silverlight will reach end of support after October 2021. Learn more.
Place the sections of code that might throw exceptions in a try block and place code that handles exceptions in a catch block. The catch block is a series of statements beginning with the keyword catch, followed by an exception type and an action to be taken.
Note: |
---|
Almost any line of code can cause an exception, particularly exceptions that are thrown by the common language runtime itself, such as OutOfMemoryException and StackOverflowException. Most applications do not have to deal with these exceptions, but you should be aware of this possibility when writing libraries to be used by others. For suggestions on when to set code in a try block, see Best Practices for Handling Exceptions. |
The following code example uses a try/catch block to catch a possible exception. The Main method contains a try block with a StreamReader statement that opens a data file called data.txt and writes a string from the file. Following the try block is a catch block that catches any exception that results from the try block.
Example
Option Explicit
Option Strict
Imports System
Imports System.IO
Imports System.Security.Permissions
<assembly: FileIOPermissionAttribute(SecurityAction.RequestMinimum, All := "c:\data.txt")>
Public Class ProcessFile
Public Shared Sub Main()
Try
Dim sr As StreamReader = File.OpenText("data.txt")
Console.WriteLine("The first line of this file is {0}", sr.ReadLine())
Catch e As Exception
Console.WriteLine("An error occurred: '{0}'", e)
End Try
End Sub
End Class
using System;
using System.IO;
using System.Security.Permissions;
// Security permission request.
[assembly:FileIOPermissionAttribute(SecurityAction.RequestMinimum, All = @"c:\data.txt")]
public class ProcessFile {
public static void Main() {
try {
StreamReader sr = File.OpenText("data.txt");
Console.WriteLine("The first line of this file is {0}", sr.ReadLine());
}
catch(Exception e) {
Console.WriteLine("An error occurred: '{0}'", e);
}
}
}
This example illustrates a basic catch statement that will catch any exception. In general, it is good programming practice to catch a specific type of exception rather than use the basic catch statement. For more information about catching specific exceptions, see Using Specific Exceptions in a Catch Block.
See Also