advertisement
The finally Statement in C#
In general, if any of the statements in the try block raises an exception, the catch block is executed and the rest of the statements in the try block are ignored. sometimes, it becomes mandatory to execute some statements irrespective of whether an exception is raised or not. In such cases, a finally block is used. Examples of actions that can be placed in a finally block are: closing a file, assigning objects to null, closing a database connection, and so forth.
The finally block is an optional block and it appears after the catch block. It encloses statements that are executed regardless of whether an exception occurs.
EXAMPLE
class divisionerror
{
static void Main(string[] args)
{
int numone = 132;
int numtwo = 2;
int result = 0; // Initialize to a default value
try
{
result = numone / numtwo;
}
catch (DivideByZeroException excobj)
{
Console.WriteLine("Exception caught: " + excobj);
}
finally
{
// Use the initialized result variable
Console.WriteLine("The result is: " + result);
}
Console.ReadKey();
}
}
The provided C# code defines a simple console application that handles division by zero using a try-catch-finally structure. Two integer variables, numone and numtwo, are initialized with values 132 and 2, respectively. The code attempts to divide numone by numtwo in a try block, and if a DivideByZeroException occurs, it catches the exception and prints an error message to the console. The finally block ensures that a message indicating the result of the division, stored in the result variable, is always displayed, promoting robust exception handling and consistent program execution.
advertisement
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0