+ 2
Can't understand why we need finally when we can just put this code after try-catch?
4 Respuestas
+ 5
Finally is needed when you want that the program do something even if theres an error or not. For example, when working with files it is necessary that close it always, because if not, later when try to open it again will have an error, it will say that the file is in used. So you put the finally to be sure to close it.
+ 5
Best programming practice. What happens in try-catch-finally, stays in try-catch-finally. If you open a file and it must be closed the right way is use "finally" for acomplish it
+ 5
For example:
1)
try {
int[] x = new int[3];
x[5] = 10;
}
catch (DivideByZeroException e) {
// Some code
}
Console.Write("Hi"); // Won't run
2)
try {
int[] x = new int[3];
x[5] = 10;
}
catch (DivideByZeroException e) {
// Some code
}
finally {
Console.Write("Hi"); // Will definitely run
}
+ 1
to make the program continue with execution.