usar try tipos sirve qué programacion para excepciones errores definicion como catch capturar c# try-catch try-catch-finally

tipos - try catch c#



¿Cómo funciona el try catch finalmente funciona? (5)

Sí, el bloque finally se ejecuta si hay una excepción o no.

Try [ tryStatements ] [ Exit Try ] [ Catch [ exception [ As type ] ] [ When expression ] [ catchStatements ] [ Exit Try ] ] [ Catch ... ] [ Finally [ finallyStatements ] ] --RUN ALWAYS End Try

Ver: http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx

En C# , ¿cómo funciona un try catch finalmente funciona?

Entonces, si hay una excepción, sé que saltará al bloque catch y luego saltará al bloque finally.

Pero, ¿y si no hay ningún error, el bloque catch no se ejecutará, pero entonces se ejecuta el bloque finally?


Sí, la cláusula finally se ejecuta si no hay 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 supongamos que se produce una excepción, finalmente se ejecuta.


Un uso común de catch y finalmente juntos es obtener y utilizar recursos en un bloque try, tratar 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, vea try-catch y Throwing Exceptions . Para obtener más información sobre el bloque finally, vea 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 se ejecuta, no importa qué. 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"); }