473,322 Members | 1,352 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Why is the compiler flagging this variable as unassigned?

Use of unassigned local variable 'fs'

Please see where I've indicated where the compiler is flagging this error in
the method below. fs is initialized in the first line in the try block, so
why is it flagged as unassigned in the finally block?

Thanks for your help!

- Joe Geretz -

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
catch (Exception e)
{
throw new Exception("Could not open " + FileSpec, e);
}
finally
{
fs.Close(); <-- Error flagged on this line
}
}
Nov 17 '05 #1
29 2217
Joseph,

The reason is compiler can not be sure of the fact that fs has been assigned
a value at that point. For instance, if exception happens during the call to
File.Open(), fs doesn't get a value assigned. Use:

FileStream fs = null;

and the compiler will stop complain.

Regards - Octavio
"Joseph Geretz" <jg*****@nospam.com> escribió en el mensaje
news:ev**************@TK2MSFTNGP09.phx.gbl...
Use of unassigned local variable 'fs'

Please see where I've indicated where the compiler is flagging this error
in the method below. fs is initialized in the first line in the try block,
so why is it flagged as unassigned in the finally block?

Thanks for your help!

- Joe Geretz -

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
catch (Exception e)
{
throw new Exception("Could not open " + FileSpec, e);
}
finally
{
fs.Close(); <-- Error flagged on this line
}
}

Nov 17 '05 #2
Joseph,

The reason is compiler can not be sure of the fact that fs has been assigned
a value at that point. For instance, if exception happens during the call to
File.Open(), fs doesn't get a value assigned. Use:

FileStream fs = null;

and the compiler will stop complain.

Regards - Octavio
"Joseph Geretz" <jg*****@nospam.com> escribió en el mensaje
news:ev**************@TK2MSFTNGP09.phx.gbl...
Use of unassigned local variable 'fs'

Please see where I've indicated where the compiler is flagging this error
in the method below. fs is initialized in the first line in the try block,
so why is it flagged as unassigned in the finally block?

Thanks for your help!

- Joe Geretz -

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
catch (Exception e)
{
throw new Exception("Could not open " + FileSpec, e);
}
finally
{
fs.Close(); <-- Error flagged on this line
}
}

Nov 17 '05 #3
The first line of your try block could immediately throw an exception
(e.g. "Access Denied"), in which case your fs variable would indeed be
unassigned in the "finally" block.

Bennie Haelen

Joseph Geretz wrote:
Use of unassigned local variable 'fs'

Please see where I've indicated where the compiler is flagging this error in
the method below. fs is initialized in the first line in the try block, so
why is it flagged as unassigned in the finally block?

Thanks for your help!

- Joe Geretz -

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
catch (Exception e)
{
throw new Exception("Could not open " + FileSpec, e);
}
finally
{
fs.Close(); <-- Error flagged on this line
}
}

Nov 17 '05 #4
The first line of your try block could immediately throw an exception
(e.g. "Access Denied"), in which case your fs variable would indeed be
unassigned in the "finally" block.

Bennie Haelen

Joseph Geretz wrote:
Use of unassigned local variable 'fs'

Please see where I've indicated where the compiler is flagging this error in
the method below. fs is initialized in the first line in the try block, so
why is it flagged as unassigned in the finally block?

Thanks for your help!

- Joe Geretz -

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
catch (Exception e)
{
throw new Exception("Could not open " + FileSpec, e);
}
finally
{
fs.Close(); <-- Error flagged on this line
}
}

Nov 17 '05 #5
Thanks guys,

I broke this up into two try/catch blocks.

- Joe Geretz -

private byte[] ReadFile(string FileSpec)
{
FileStream fs;

try // Open File
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
}
catch (Exception e)
{
throw new Exception("Could not open " + FileSpec, e);
}

try // Read file contents
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen];
fs.Read(FileBuffer, 0, FileLen);
fs.Close();
return FileBuffer;
}
catch (Exception e)
{
throw new Exception("Could not read from " + FileSpec, e);
}
finally
{
fs.Close();
}
}

"Bennie Haelen" <Be***********@jda.com> wrote in message
news:eG**************@TK2MSFTNGP14.phx.gbl...
The first line of your try block could immediately throw an exception
(e.g. "Access Denied"), in which case your fs variable would indeed be
unassigned in the "finally" block.

Bennie Haelen

Joseph Geretz wrote:
Use of unassigned local variable 'fs'

Please see where I've indicated where the compiler is flagging this error
in the method below. fs is initialized in the first line in the try
block, so why is it flagged as unassigned in the finally block?

Thanks for your help!

- Joe Geretz -

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
catch (Exception e)
{
throw new Exception("Could not open " + FileSpec, e);
}
finally
{
fs.Close(); <-- Error flagged on this line
}
}

Nov 17 '05 #6
Thanks guys,

I broke this up into two try/catch blocks.

- Joe Geretz -

private byte[] ReadFile(string FileSpec)
{
FileStream fs;

try // Open File
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
}
catch (Exception e)
{
throw new Exception("Could not open " + FileSpec, e);
}

try // Read file contents
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen];
fs.Read(FileBuffer, 0, FileLen);
fs.Close();
return FileBuffer;
}
catch (Exception e)
{
throw new Exception("Could not read from " + FileSpec, e);
}
finally
{
fs.Close();
}
}

"Bennie Haelen" <Be***********@jda.com> wrote in message
news:eG**************@TK2MSFTNGP14.phx.gbl...
The first line of your try block could immediately throw an exception
(e.g. "Access Denied"), in which case your fs variable would indeed be
unassigned in the "finally" block.

Bennie Haelen

Joseph Geretz wrote:
Use of unassigned local variable 'fs'

Please see where I've indicated where the compiler is flagging this error
in the method below. fs is initialized in the first line in the try
block, so why is it flagged as unassigned in the finally block?

Thanks for your help!

- Joe Geretz -

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
catch (Exception e)
{
throw new Exception("Could not open " + FileSpec, e);
}
finally
{
fs.Close(); <-- Error flagged on this line
}
}

Nov 17 '05 #7
Joseph Geretz <jg*****@nospam.com> wrote:
I broke this up into two try/catch blocks.


I'm not sure why you want to catch the exception in the first place. I
don't think you're adding much information to it, and you're taking
away the information given by the type of the exception - no-one could
catch FileNotFoundException, for instance, because you're just throwing
a plain Exception.

I'd just change it to:

using (FileStream fs = File.Open (...))
{
// Do the read and return
}

Note also that you're assuming a FileStream will always read the whole
of the data in one go. That *may* be true for a FileStream (I haven't
seen it fail yet) but it's not a good habit to get into. See
http://www.pobox.com/~skeet/csharp/readbinary.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
Joseph Geretz <jg*****@nospam.com> wrote:
I broke this up into two try/catch blocks.


I'm not sure why you want to catch the exception in the first place. I
don't think you're adding much information to it, and you're taking
away the information given by the type of the exception - no-one could
catch FileNotFoundException, for instance, because you're just throwing
a plain Exception.

I'd just change it to:

using (FileStream fs = File.Open (...))
{
// Do the read and return
}

Note also that you're assuming a FileStream will always read the whole
of the data in one go. That *may* be true for a FileStream (I haven't
seen it fail yet) but it's not a good habit to get into. See
http://www.pobox.com/~skeet/csharp/readbinary.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9
Joe,

I guess I'd write your code this way:

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
// if file was successfully opened, we should close it,
// no matter wheter there is an exception or not during read
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}
}
catch (Exception e)
{
throw new ApplicationException("Could not open " + FileSpec, e);
}

Personally, I never use full try-catch-finally constructs. I believe
(languages like Modula-3 or Delphi propose this approach) that TRY-FINALLY
and TRY-CATCH are two very different kinds of beast, and that combining them
into a single construction is not a good idea. But I guess some people may
disagree with this.

Regarding the outer try-catch, its only goal is to encapsulate the original
exception into a new one, and we possibly could live without it. By the way,
there is an excelent post on the subject by Helge Jensen a few threads below
this one.

Regards - Octavio

Nov 17 '05 #10
Joe,

I guess I'd write your code this way:

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
// if file was successfully opened, we should close it,
// no matter wheter there is an exception or not during read
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}
}
catch (Exception e)
{
throw new ApplicationException("Could not open " + FileSpec, e);
}

Personally, I never use full try-catch-finally constructs. I believe
(languages like Modula-3 or Delphi propose this approach) that TRY-FINALLY
and TRY-CATCH are two very different kinds of beast, and that combining them
into a single construction is not a good idea. But I guess some people may
disagree with this.

Regarding the outer try-catch, its only goal is to encapsulate the original
exception into a new one, and we possibly could live without it. By the way,
there is an excelent post on the subject by Helge Jensen a few threads below
this one.

Regards - Octavio

Nov 17 '05 #11
Hi Jon,

Thanks for the suggestion regarding the using construct. I agree that this
is a more useful approach for this situation.

And you're right about the FileStream as well. As soon as you encounter a
file with more than an int's worth of bytes (how much is that by the way?)
you're going to need more than a single read. At this point I'm just working
on an early proof of concept. The file I'm working with contains 'Hello
World!' so I'm in no danger :-)

The catch block is just a preliminary placeholder. But why do you say I'm
suppressing the original error? doesn't throw new Exception("message", e);
include the original Exception (e) in the Exception stack?

Thanks for your advice,

- Joe Geretz -

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Joseph Geretz <jg*****@nospam.com> wrote:
I broke this up into two try/catch blocks.


I'm not sure why you want to catch the exception in the first place. I
don't think you're adding much information to it, and you're taking
away the information given by the type of the exception - no-one could
catch FileNotFoundException, for instance, because you're just throwing
a plain Exception.

I'd just change it to:

using (FileStream fs = File.Open (...))
{
// Do the read and return
}

Note also that you're assuming a FileStream will always read the whole
of the data in one go. That *may* be true for a FileStream (I haven't
seen it fail yet) but it's not a good habit to get into. See
http://www.pobox.com/~skeet/csharp/readbinary.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #12
Hi Jon,

Thanks for the suggestion regarding the using construct. I agree that this
is a more useful approach for this situation.

And you're right about the FileStream as well. As soon as you encounter a
file with more than an int's worth of bytes (how much is that by the way?)
you're going to need more than a single read. At this point I'm just working
on an early proof of concept. The file I'm working with contains 'Hello
World!' so I'm in no danger :-)

The catch block is just a preliminary placeholder. But why do you say I'm
suppressing the original error? doesn't throw new Exception("message", e);
include the original Exception (e) in the Exception stack?

Thanks for your advice,

- Joe Geretz -

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Joseph Geretz <jg*****@nospam.com> wrote:
I broke this up into two try/catch blocks.


I'm not sure why you want to catch the exception in the first place. I
don't think you're adding much information to it, and you're taking
away the information given by the type of the exception - no-one could
catch FileNotFoundException, for instance, because you're just throwing
a plain Exception.

I'd just change it to:

using (FileStream fs = File.Open (...))
{
// Do the read and return
}

Note also that you're assuming a FileStream will always read the whole
of the data in one go. That *may* be true for a FileStream (I haven't
seen it fail yet) but it's not a good habit to get into. See
http://www.pobox.com/~skeet/csharp/readbinary.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #13
Hi Octavio,

Thanks for your suggestion. I'll keep nesting in mind for the future.
there is an excelent post on the subject by Helge Jensen a few threads
below this one.
I'd like to take a look at this but I don't see the post you refer to. Can
you provide me with the title of the post?

Thanks,

Joe Geretz

"Octavio Hernandez" <do****@danysoft.com> wrote in message
news:eM**************@TK2MSFTNGP12.phx.gbl... Joe,

I guess I'd write your code this way:

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
// if file was successfully opened, we should close it,
// no matter wheter there is an exception or not during read
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}
}
catch (Exception e)
{
throw new ApplicationException("Could not open " + FileSpec, e);
}

Personally, I never use full try-catch-finally constructs. I believe
(languages like Modula-3 or Delphi propose this approach) that TRY-FINALLY
and TRY-CATCH are two very different kinds of beast, and that combining
them into a single construction is not a good idea. But I guess some
people may disagree with this.

Regarding the outer try-catch, its only goal is to encapsulate the
original exception into a new one, and we possibly could live without it.
By the way, there is an excelent post on the subject by Helge Jensen a few
threads below this one.

Regards - Octavio

Nov 17 '05 #14
Hi Octavio,

Thanks for your suggestion. I'll keep nesting in mind for the future.
there is an excelent post on the subject by Helge Jensen a few threads
below this one.
I'd like to take a look at this but I don't see the post you refer to. Can
you provide me with the title of the post?

Thanks,

Joe Geretz

"Octavio Hernandez" <do****@danysoft.com> wrote in message
news:eM**************@TK2MSFTNGP12.phx.gbl... Joe,

I guess I'd write your code this way:

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
// if file was successfully opened, we should close it,
// no matter wheter there is an exception or not during read
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}
}
catch (Exception e)
{
throw new ApplicationException("Could not open " + FileSpec, e);
}

Personally, I never use full try-catch-finally constructs. I believe
(languages like Modula-3 or Delphi propose this approach) that TRY-FINALLY
and TRY-CATCH are two very different kinds of beast, and that combining
them into a single construction is not a good idea. But I guess some
people may disagree with this.

Regarding the outer try-catch, its only goal is to encapsulate the
original exception into a new one, and we possibly could live without it.
By the way, there is an excelent post on the subject by Helge Jensen a few
threads below this one.

Regards - Octavio

Nov 17 '05 #15
> I'd like to take a look at this but I don't see the post you refer to. Can
you provide me with the title of the post?
Cancel that. I see the post which was started by clintonG.

"Joseph Geretz" <jg*****@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl... Hi Octavio,

Thanks for your suggestion. I'll keep nesting in mind for the future.
there is an excelent post on the subject by Helge Jensen a few threads
below this one.


I'd like to take a look at this but I don't see the post you refer to. Can
you provide me with the title of the post?

Thanks,

Joe Geretz

"Octavio Hernandez" <do****@danysoft.com> wrote in message
news:eM**************@TK2MSFTNGP12.phx.gbl...
Joe,

I guess I'd write your code this way:

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
// if file was successfully opened, we should close it,
// no matter wheter there is an exception or not during read
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}
}
catch (Exception e)
{
throw new ApplicationException("Could not open " + FileSpec, e);
}

Personally, I never use full try-catch-finally constructs. I believe
(languages like Modula-3 or Delphi propose this approach) that
TRY-FINALLY and TRY-CATCH are two very different kinds of beast, and that
combining them into a single construction is not a good idea. But I guess
some people may disagree with this.

Regarding the outer try-catch, its only goal is to encapsulate the
original exception into a new one, and we possibly could live without it.
By the way, there is an excelent post on the subject by Helge Jensen a
few threads below this one.

Regards - Octavio


Nov 17 '05 #16
> I'd like to take a look at this but I don't see the post you refer to. Can
you provide me with the title of the post?
Cancel that. I see the post which was started by clintonG.

"Joseph Geretz" <jg*****@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl... Hi Octavio,

Thanks for your suggestion. I'll keep nesting in mind for the future.
there is an excelent post on the subject by Helge Jensen a few threads
below this one.


I'd like to take a look at this but I don't see the post you refer to. Can
you provide me with the title of the post?

Thanks,

Joe Geretz

"Octavio Hernandez" <do****@danysoft.com> wrote in message
news:eM**************@TK2MSFTNGP12.phx.gbl...
Joe,

I guess I'd write your code this way:

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
// if file was successfully opened, we should close it,
// no matter wheter there is an exception or not during read
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}
}
catch (Exception e)
{
throw new ApplicationException("Could not open " + FileSpec, e);
}

Personally, I never use full try-catch-finally constructs. I believe
(languages like Modula-3 or Delphi propose this approach) that
TRY-FINALLY and TRY-CATCH are two very different kinds of beast, and that
combining them into a single construction is not a good idea. But I guess
some people may disagree with this.

Regarding the outer try-catch, its only goal is to encapsulate the
original exception into a new one, and we possibly could live without it.
By the way, there is an excelent post on the subject by Helge Jensen a
few threads below this one.

Regards - Octavio


Nov 17 '05 #17
Joseph Geretz <jg*****@nospam.com> wrote:
Thanks for the suggestion regarding the using construct. I agree that this
is a more useful approach for this situation.

And you're right about the FileStream as well. As soon as you encounter a
file with more than an int's worth of bytes (how much is that by the way?)
you're going to need more than a single read. At this point I'm just working
on an early proof of concept. The file I'm working with contains 'Hello
World!' so I'm in no danger :-)

The catch block is just a preliminary placeholder. But why do you say I'm
suppressing the original error? doesn't throw new Exception("message", e);
include the original Exception (e) in the Exception stack


Yes, the information is still there, but it can't be used as usefully -
if I do:

catch (IOException e)

because I know what to do with IOExceptions, but I don't know what to
do with any other kind of exception, I won't catch your exception.
Instead, I've got to do:

catch (Exception e)
{
if (e.InnerException is IOException)
{
...
}
else
{
throw;
}
}

which is ugly.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #18
Joseph Geretz <jg*****@nospam.com> wrote:
Thanks for the suggestion regarding the using construct. I agree that this
is a more useful approach for this situation.

And you're right about the FileStream as well. As soon as you encounter a
file with more than an int's worth of bytes (how much is that by the way?)
you're going to need more than a single read. At this point I'm just working
on an early proof of concept. The file I'm working with contains 'Hello
World!' so I'm in no danger :-)

The catch block is just a preliminary placeholder. But why do you say I'm
suppressing the original error? doesn't throw new Exception("message", e);
include the original Exception (e) in the Exception stack


Yes, the information is still there, but it can't be used as usefully -
if I do:

catch (IOException e)

because I know what to do with IOExceptions, but I don't know what to
do with any other kind of exception, I won't catch your exception.
Instead, I've got to do:

catch (Exception e)
{
if (e.InnerException is IOException)
{
...
}
else
{
throw;
}
}

which is ugly.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #19
Joe,

One more observation that came to mind after reading John's post.
If you remove completely the try-catch construct from my code, it will only
remain:

FileStream fs;
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}

which is precisely the semantics of the using statement:

using (FileStream fs = File.Open(FileSpec, FileMode.Open,
FileAccess.Read))
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}

Regards - Octavio

"Joseph Geretz" <jg*****@nospam.com> escribió en el mensaje
news:%2****************@TK2MSFTNGP12.phx.gbl...
Hi Octavio,

Thanks for your suggestion. I'll keep nesting in mind for the future.
there is an excelent post on the subject by Helge Jensen a few threads
below this one.


I'd like to take a look at this but I don't see the post you refer to. Can
you provide me with the title of the post?

Thanks,

Joe Geretz

"Octavio Hernandez" <do****@danysoft.com> wrote in message
news:eM**************@TK2MSFTNGP12.phx.gbl...
Joe,

I guess I'd write your code this way:

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
// if file was successfully opened, we should close it,
// no matter wheter there is an exception or not during read
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}
}
catch (Exception e)
{
throw new ApplicationException("Could not open " + FileSpec, e);
}

Personally, I never use full try-catch-finally constructs. I believe
(languages like Modula-3 or Delphi propose this approach) that
TRY-FINALLY and TRY-CATCH are two very different kinds of beast, and that
combining them into a single construction is not a good idea. But I guess
some people may disagree with this.

Regarding the outer try-catch, its only goal is to encapsulate the
original exception into a new one, and we possibly could live without it.
By the way, there is an excelent post on the subject by Helge Jensen a
few threads below this one.

Regards - Octavio


Nov 17 '05 #20
Joe,

One more observation that came to mind after reading John's post.
If you remove completely the try-catch construct from my code, it will only
remain:

FileStream fs;
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}

which is precisely the semantics of the using statement:

using (FileStream fs = File.Open(FileSpec, FileMode.Open,
FileAccess.Read))
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}

Regards - Octavio

"Joseph Geretz" <jg*****@nospam.com> escribió en el mensaje
news:%2****************@TK2MSFTNGP12.phx.gbl...
Hi Octavio,

Thanks for your suggestion. I'll keep nesting in mind for the future.
there is an excelent post on the subject by Helge Jensen a few threads
below this one.


I'd like to take a look at this but I don't see the post you refer to. Can
you provide me with the title of the post?

Thanks,

Joe Geretz

"Octavio Hernandez" <do****@danysoft.com> wrote in message
news:eM**************@TK2MSFTNGP12.phx.gbl...
Joe,

I guess I'd write your code this way:

private byte[] ReadFile(string FileSpec)
{
FileStream fs;
try
{
fs = File.Open(FileSpec, FileMode.Open, FileAccess.Read);
// if file was successfully opened, we should close it,
// no matter wheter there is an exception or not during read
try
{
int FileLen = (int) fs.Length;
byte[] FileBuffer = new byte[FileLen -1];
fs.Read(FileBuffer, 0, FileLen);
return FileBuffer;
}
finally
{
fs.Close();
}
}
catch (Exception e)
{
throw new ApplicationException("Could not open " + FileSpec, e);
}

Personally, I never use full try-catch-finally constructs. I believe
(languages like Modula-3 or Delphi propose this approach) that
TRY-FINALLY and TRY-CATCH are two very different kinds of beast, and that
combining them into a single construction is not a good idea. But I guess
some people may disagree with this.

Regarding the outer try-catch, its only goal is to encapsulate the
original exception into a new one, and we possibly could live without it.
By the way, there is an excelent post on the subject by Helge Jensen a
few threads below this one.

Regards - Octavio


Nov 17 '05 #21
> catch (Exception e)
{
if (e.InnerException is IOException)
{
...
}
else
{
throw;
}
}

which is ugly.
Right, but to refer to your stement from our conversation in a related
thread: Try Catch Implementation Guidelines
most errors are unrecoverable for
that unit of work, which usually goes right up to the top level.
Agreed. I'm not interested in analyzing or processing exceptions in code,
except to accumulate as much information regarding the state of the software
at the time the error occurred so that when this information finally reaches
the UI level, some developer can take a look at this and figure out what
went wrong and how to fix it. Unless .NET Exceptions natively add Stack and
State information to the Exception object as the stack unwinds, I'll need to
implement my own covering Catch block in every method to do this myself.

No?

- Joe Geretz -

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om... Joseph Geretz <jg*****@nospam.com> wrote:
Thanks for the suggestion regarding the using construct. I agree that
this
is a more useful approach for this situation.

And you're right about the FileStream as well. As soon as you encounter a
file with more than an int's worth of bytes (how much is that by the
way?)
you're going to need more than a single read. At this point I'm just
working
on an early proof of concept. The file I'm working with contains 'Hello
World!' so I'm in no danger :-)

The catch block is just a preliminary placeholder. But why do you say I'm
suppressing the original error? doesn't throw new Exception("message",
e);
include the original Exception (e) in the Exception stack


Yes, the information is still there, but it can't be used as usefully -
if I do:

catch (IOException e)

because I know what to do with IOExceptions, but I don't know what to
do with any other kind of exception, I won't catch your exception.
Instead, I've got to do:

catch (Exception e)
{
if (e.InnerException is IOException)
{
...
}
else
{
throw;
}
}

which is ugly.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #22
Joseph Geretz <jg*****@nospam.com> wrote:

<snip>
most errors are unrecoverable for
that unit of work, which usually goes right up to the top level.


Agreed. I'm not interested in analyzing or processing exceptions in code,
except to accumulate as much information regarding the state of the software
at the time the error occurred so that when this information finally reaches
the UI level, some developer can take a look at this and figure out what
went wrong and how to fix it. Unless .NET Exceptions natively add Stack and
State information to the Exception object as the stack unwinds, I'll need to
implement my own covering Catch block in every method to do this myself.

No?


See my reply in another thread - basically, you get stack information,
and the exception message should usually give you enough information to
know what's going on. All of that is given for free, without having to
put try/catch in every method. If the framework designers had

Even if you add your own state information, you've got to work out
*all* the information you could possibly need - what if one of your
variables is a hash table with millions of entries? Are you going to
put all of that in a log file?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #23
Hi Jon,

I saw your reply in the other thread as well. Thanks.
Even if you add your own state information, you've got to work out
*all* the information you could possibly need - what if one of your
variables is a hash table with millions of entries? Are you going to
put all of that in a log file?
No, of course not. But let's not let the perfect be the enemy of the good.

In the most minimal implementation we capture the name of the current method
which builds us a stack trace as the stack unwinds. This is already a heck
of an improvement over VB6 native capabilities. (As you've mentioned
elsewhere this is provided natively with the new .NET exception
architecture.)

In the next level of implementation, the developer adds method local
variables onto the StackTrace. Do we capture all local state? No. But
getting some state is better than no state, especially if the state we
capture does in fact include the cause of the problem.

We do encounter runtime errors which don't include enough state information.
Even so, we at least have the stack trace which helps us. What we'll do in
this situation is, when the developer goes into the problematic method to
fix the code, the devleoper will also beef up the stack trace handler to
include additional state information.

While it's not perfect, over several product versions the error handling has
evolved to the point where more than 90% of our runtime errors are
immediately identifiable. We're software vendors and rarely have convenient
access to our customers' environments. So it's important for us to be able
to capture as much information as possible at the point of failure in order
to be able to diagnose the problem remotely. This is a deficiency in the VB6
native error handling facility, but we've been able to largely close the
breach with this approach. I've used this approach with great success in
numerous VB6 applications.

- Joe Geretz -

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om... Joseph Geretz <jg*****@nospam.com> wrote:

<snip>
> most errors are unrecoverable for
> that unit of work, which usually goes right up to the top level.


Agreed. I'm not interested in analyzing or processing exceptions in code,
except to accumulate as much information regarding the state of the
software
at the time the error occurred so that when this information finally
reaches
the UI level, some developer can take a look at this and figure out what
went wrong and how to fix it. Unless .NET Exceptions natively add Stack
and
State information to the Exception object as the stack unwinds, I'll need
to
implement my own covering Catch block in every method to do this myself.

No?


See my reply in another thread - basically, you get stack information,
and the exception message should usually give you enough information to
know what's going on. All of that is given for free, without having to
put try/catch in every method. If the framework designers had

Even if you add your own state information, you've got to work out
*all* the information you could possibly need - what if one of your
variables is a hash table with millions of entries? Are you going to
put all of that in a log file?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #24
"Joseph Geretz" <jg*****@nospam.com> schrieb im Newsbeitrag
news:%2****************@TK2MSFTNGP15.phx.gbl...
<snip>
In the most minimal implementation we capture the name of the current
method which builds us a stack trace as the stack unwinds. <snip>

That's exactly the soluion Jon Skeet porposed, since the information IS
already there
in the Exception class.
(Simply put exc.ToString() in your error log.)

<snip> While it's not perfect, over several product versions the error handling
has evolved to the point where more than 90% of our runtime errors are
immediately identifiable.

<snip>

I think, that's almost the place, where we already are ;)

Christof
Nov 17 '05 #25
> I think, that's almost the place, where we already are ;)

Already? When did you arrive? I've been doing this with VB6 since the mid to
late '90's!

I think the point which you may have missed is that the implementation I'm
speaking of is a VB6 implementation which predates the .NET solution by
nearly half a decade!

- Joe Geretz -

"Christof Nordiek" <cn@nospam.de> wrote in message
news:%2***************@tk2msftngp13.phx.gbl...
"Joseph Geretz" <jg*****@nospam.com> schrieb im Newsbeitrag
news:%2****************@TK2MSFTNGP15.phx.gbl...
<snip>
In the most minimal implementation we capture the name of the current
method which builds us a stack trace as the stack unwinds.

<snip>

That's exactly the soluion Jon Skeet porposed, since the information IS
already there
in the Exception class.
(Simply put exc.ToString() in your error log.)

<snip>
While it's not perfect, over several product versions the error handling
has evolved to the point where more than 90% of our runtime errors are
immediately identifiable.

<snip>

I think, that's almost the place, where we already are ;)

Christof

Nov 17 '05 #26
Joseph Geretz <jg*****@nospam.com> wrote:
I think, that's almost the place, where we already are ;)


Already? When did you arrive? I've been doing this with VB6 since the mid to
late '90's!

I think the point which you may have missed is that the implementation I'm
speaking of is a VB6 implementation which predates the .NET solution by
nearly half a decade!


Well, it's also been the situation Java's been in since 1995 - but
without having to decorate every method.

(It may well have been available in other languages/runtimes before
that, of course...)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #27
I didn't see this in any of the replies, but if you write the catch block
like this:

catch( exception ex)
{
throw;
}

you will rethrow the exception that you received with no changes. All
information will be retained. You will, however get a warning for not using
ex. This will allow you to place a break on the catch block for
troubleshooting purposes and view ex to see what is going on.

Chuck
Nov 17 '05 #28
Well why not

catch (Exception ex)
{
throw ex;
}

Doesn't this achieve the same effect without the warning?

- Joe Geretz -

"noisemaker" <no********@discussions.microsoft.com> wrote in message
news:E2**********************************@microsof t.com...
I didn't see this in any of the replies, but if you write the catch block
like this:

catch( exception ex)
{
throw;
}

you will rethrow the exception that you received with no changes. All
information will be retained. You will, however get a warning for not
using
ex. This will allow you to place a break on the catch block for
troubleshooting purposes and view ex to see what is going on.

Chuck

Nov 17 '05 #29
Joseph Geretz <jg*****@nospam.com> wrote:
Well why not

catch (Exception ex)
{
throw ex;
}

Doesn't this achieve the same effect without the warning?


No. If you use a bare "throw;" the original stack trace is preserved.
If you use "throw ex;" the stack trace is "restarted" from the throw
statement.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Ivan Marsh | last post by:
Hey Folks, Anyone know how to test for the existance of a variable in javascript? I'm looking for the equivalent of IsSet() from PHP. I'm having trouble finding it. thx --
3
by: Mike P | last post by:
I keep getting the error 'Use of unassigned local variable' in my code, which I have used before and it works fine : SqlTransaction Trans1, Trans2; SqlConnection...
9
by: Ropo | last post by:
Newbie: I am writing code to read an xml file. I want two values from the document so I want to save them as I am reading through the elements. I want to reference them (using Console.WriteLine)...
3
by: John Smith | last post by:
In the following (pseudo)code, why is it that C# returns an "unassigned local variable" error for nVar? It seems I have to declare the variable outside foo() for the error to dissapear. void...
2
by: kaiser | last post by:
Hello I am trying to get the last lines value in a text file and display it on screen / read it into a variable. When I run the following code in a console I get the following error "Use...
0
by: Joseph Geretz | last post by:
Use of unassigned local variable 'fs' Please see where I've indicated where the compiler is flagging this error in the method below. fs is initialized in the first line in the try block, so why...
12
by: Bernie V | last post by:
Hi group, I'm trying to do this: String DatVandaag; DatVandaag=DateTime.Today.AddDays(-2).ToString("dd/MM/yyyy"); LiteralHeat.Text = "<center><H5>Wekelijkse vinyl TOP 10...
9
by: tshad | last post by:
I am getting an error: Use of unassigned local variable 'postDateRow' But it is assigned. Here is the code: int payDateRow; int postDateRow;
49
by: valentin tihomirov | last post by:
fDeleted = false; uint jobId; foreach (Struct struct in structures) { if (struct.type == JOB) { jobId = struct.id; if (struct.dataType == STATUS) fDeteted = (struct.data & STATUS_DELETED) !=...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.