En C#
, ¿cómo funciona un locking de prueba finalmente bloquear el trabajo?
Entonces, si hay una excepción, sé que saltará al bloque catch y luego saltará al bloque finally.
Pero ¿qué pasa si no hay un error, el bloque catch no se ejecuta, pero el bloque finalmente se ejecuta entonces?
Sí, el bloque finally se ejecuta, ya sea que haya una excepción o no.
Tratar [tryStatements] [Salir de prueba] [Captura [excepción [Como tipo]] [Cuando expresión] [catchStatements] [Exit Try]] [ Captura ... ] [ Finalmente [finalmente Declaraciones]] - EJECUTAR SIEMPRE Prueba final
Consulte: http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx
Sí, la cláusula finalmente se pone en práctica si no hay una excepción. Tomando un ejemplo
try { int a = 10; int b = 20; int z = a + b; } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.WriteLine("Executed"); }
Entonces, si suponemos que se produce una excepción, también se ejecuta finalmente.
Un uso común de catch y finalmente en conjunto es obtener y usar recursos en un bloque try, lidiar con circunstancias excepcionales en un bloque catch y liberar los recursos en el bloque finally.
Para obtener más información y ejemplos sobre cómo volver a lanzar excepciones, consulte las excepciones Try-catch y Throwing . Para obtener más información sobre el bloque finally, consulte try-finally .
public class EHClass { void ReadFile(int index) { // To run this code, substitute a valid path from your local machine string path = @"c:\users\public\test.txt"; System.IO.StreamReader file = new System.IO.StreamReader(path); char[] buffer = new char[10]; try { file.ReadBlock(buffer, index, buffer.Length); } catch (System.IO.IOException e) { Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message); } finally { if (file != null) { file.Close(); } } // Do something with buffer... } }
Finalmente el bloque siempre corre, pase lo que pase. solo prueba este método
public int TryCatchFinally(int a, int b) { try { int sum = a + b; if (a > b) { throw new Exception(); } else { int rightreturn = 2; return rightreturn; } } catch (Exception) { int ret = 1; return ret; } finally { int fin = 5; } }
try { //Function to Perform } catch (Exception e) { //You can display what error occured in Try block, with exact technical spec (DivideByZeroException) throw; // Displaying error through signal to Machine, //throw is usefull , if you calling a method with try from derived class.. So the method will directly get the signal } finally //Optional { //Here You can write any code to be executed after error occured in Try block Console.WriteLine("Completed"); }