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,
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.
using namespace System;
using namespace System::IO;
public ref 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());
sr->Close();
}
catch (Exception^ e)
{
Console::WriteLine("An error occurred: '{0}'", e);
}
}
};
int main()
{
ProcessFile::Main();
}