Alex Rivera | Logout

C# "Using" Syntax

Asked 2008-09-29T16:55:23.743
51

Does the using catch the exception or throw it? i.e.

using (StreamReader rdr = File.OpenText("file.txt"))
{
 //do stuff
}

If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it?

Edit
Report

1 Answer

6

It throws the exception, so either your containing method needs to handle it, or pass it up the stack.

try
{
    using (
        StreamReader rdr = File.OpenText("file.txt"))
    { //do stuff 
    }
}
catch (FileNotFoundException Ex)
{
    // The file didn't exist
}
catch (AccessViolationException Ex)
{
    // You don't have the permission to open this
}
catch (Exception Ex)
{
    // Something happened! 
}
answered 2008-09-29T17:01:17.677

Your Answer