Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
When an exception occurs, execution stops and control is given to the appropriate exception handler. This often means that lines of code you expect to be executed are bypassed. Some resource cleanup, such as closing a file, needs to be done even if an exception is thrown. To do this, you can use a finally
block. A finally
block always executes, regardless of whether an exception is thrown.
The following code example uses a try
/catch
block to catch an ArgumentOutOfRangeException. The Main
method creates two arrays and attempts to copy one to the other. The action generates an ArgumentOutOfRangeException because length
is specified as -1, and the error is written to the console. The finally
block executes regardless of the outcome of the copy action.
using namespace System;
ref class ArgumentOutOfRangeExample
{
public:
static void Main()
{
array<int>^ array1 = {0, 0};
array<int>^ array2 = {0, 0};
try
{
Array::Copy(array1, array2, -1);
}
catch (ArgumentOutOfRangeException^ e)
{
Console::WriteLine("Error: {0}", e);
throw;
}
finally
{
Console::WriteLine("This statement is always executed.");
}
}
};
int main()
{
ArgumentOutOfRangeExample::Main();
}
class ArgumentOutOfRangeExample
{
public static void Main()
{
int[] array1 = {0, 0};
int[] array2 = {0, 0};
try
{
Array.Copy(array1, array2, -1);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("Error: {0}", e);
throw;
}
finally
{
Console.WriteLine("This statement is always executed.");
}
}
}
Class ArgumentOutOfRangeExample
Public Shared Sub Main()
Dim array1() As Integer = {0, 0}
Dim array2() As Integer = {0, 0}
Try
Array.Copy(array1, array2, -1)
Catch e As ArgumentOutOfRangeException
Console.WriteLine("Error: {0}", e)
Throw
Finally
Console.WriteLine("This statement is always executed.")
End Try
End Sub
End Class
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowTraining
Module
Implement exception handling in C# console applications - Training
This module explores the use of exceptions and the exception handling process in C# console applications. Hands-on activities provide experience implementing exception handling patterns for various coding scenarios.