I recently discussed with a coworker who told me that I was managing incorrently a stream into a try / catch / block. So I wanna know what would be a good approach for you.
try
{
StreamReader sr = new StreamReader("TestFile.txt");
//After that, here an operation of about 30 seconds to fulfill;
}
catch (IOException ioex)
{
throw new IOException("An error occurred while processing the file.", ioex);
}
catch (Exception ex)
{
throw new Exception("An generic error ocurred.");
}
finally
{
if(sr != null){
stream.Close();
stream = null;
}
}
He stated that having 2 Exception are unnecessary, even using the IOException. We can use only Exception. But the only thing that I want is to recognize where exactly the exception has been produced, because after opening the file, an operation of about 30 seconds will be performed.
So what would you think? We saw this MS example (http://msdn.microsoft.com/fr-Fr/library/system.io.streamreader.aspx) which it's simplier but in terms of performance or clean code, you find something strange?
Your opinions please!
-EDIT-----------------
Ok, I see the point but we were discussing about the Catch IOException and just using the Exception. In my opinion, like as in the example above you can know where the error ocurred; at the moment of managing the file or in the process after opening the file. That's my first question. And now, what do you think about this change below.
try
{
using(StreamReader sr = new StreamReader("TestFile.txt"))
{
//After that, here an operation of about 30 seconds to fulfill;
}
}
catch (Exception ex)
{
throw new Exception("An generic error ocurred.");
}
finally
{
if(sr != null){
stream.Close();
stream = null;
}
}
-------------------EDIT 2------------------------
Finally, I hope this would be my final solution. Thank you so much for your answers. So using is faster, efficient and just one exception is necessary.
try
{
using (StreamReader stream = sr = new StreamReader("TestFile.txt"))
{
//Operation
}
}
catch (Exception e)
{
throw new Exception(String.Format("An error ocurred while executing the data import: {0}", e.Message), e);
}
Any other comment would be appreciated!