Introduction
The finally block lets you run code that must happen no matter what, like cleaning up or closing files.
Jump into concepts and practice - no test required
The finally block lets you run code that must happen no matter what, like cleaning up or closing files.
try { // code that might cause an error } catch (Exception e) { // code to handle the error } finally { // code that always runs }
The finally block runs after try and catch, no matter what.
You can use finally with or without a catch block.
finally block without a catch. The message in finally always prints.try { Console.WriteLine("Trying something..."); } finally { Console.WriteLine("Always runs."); }
finally block.try { int x = 5 / 0; } catch (DivideByZeroException e) { Console.WriteLine("Caught division by zero."); } finally { Console.WriteLine("Cleanup code runs."); }
This program tries to divide by zero, catches the error, and then runs the finally block. The program then continues normally.
using System; class Program { static void Main() { try { Console.WriteLine("Start try block."); int result = 10 / 0; // This causes an error Console.WriteLine("This line will not run."); } catch (DivideByZeroException) { Console.WriteLine("Caught division by zero error."); } finally { Console.WriteLine("Finally block always runs."); } Console.WriteLine("Program continues."); } }
If there is a return inside try or catch, the finally block still runs before returning.
Use finally to release resources like files or connections safely.
The finally block runs no matter what happens in try or catch.
It is useful for cleanup tasks that must always happen.
You can use finally with or without catch.
finally block in C# exception handling?finallyfinally block runs after the try and catch blocks, no matter what happens.finally block in C#?try, then catch (optional), then finally (optional).try { } catch { } finally { }.try {
Console.WriteLine("Start");
throw new Exception();
} catch {
Console.WriteLine("Caught");
} finally {
Console.WriteLine("Finally");
}finally block runs printing "Finally".try {
Console.WriteLine("Hello");
} finally {
Console.WriteLine("Cleanup");
} catch (Exception ex) {
Console.WriteLine("Error");
}finally block must come after all catch blocks.finally before catch, which is invalid syntax.finally block must come after catch -> Option Dint result = 0;
try {
result = 10 / 0;
} catch (DivideByZeroException) {
result = 1;
} finally {
result = 2;
}
Console.WriteLine(result);DivideByZeroException, caught by catch which sets result = 1.finally block runs after catch and sets result = 2, overwriting previous value.