Quelle est la différence entre l'utilisation finalementPoint d'essai attraper enfin des blocs?
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...
}
et ne pas l'utiliser?
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);
}
if (file != null)
{
file.Close();
}
// Do something with buffer...
}
Le bloc catch peut renvoyer l'erreur, en déclencher un nouveau, etc., qui contournera la fermeture de finally. Voir ici - http://stackoverflow.com/questions/50618/what-is-the-point-of-the-finally-block – StuartLC
Je sais que quelqu'un d'autre va taper une réponse plus vite que je peux, mais avez-vous considéré causer un IOException et voir la différence par vous-même? – ChaosPandion