Error handling

  • Thread starter Thread starter David
  • Start date Start date
D

David

How should sockets, filestreams, and anything else that needs to be closed
be handled using try/catch/finally blocks? The only solution I can see is
to make the objects public or use a public flag that the error handler can
set so that the rest of the cold can clean up after the error handler has
run (in my case when a hard close is performed my socket loses connection
and throws an error- I need to close it after the error so it can listen for
another connection.)
 
You can declare variable of required type just before try, assign it value
(e.g. = new ...) inside the try block and close it (dispose) in finally
block.

Also, if object implements IDisposable, you can use using(){} statement to
dispose it properly when no errors.

Where do you have problems requiring you to use publics (globals)? Why
public is the only solution?
 
David said:
How should sockets, filestreams, and anything else that needs to be closed
be handled using try/catch/finally blocks? The only solution I can see is
to make the objects public or use a public flag that the error handler can
set so that the rest of the cold can clean up after the error handler has
run (in my case when a hard close is performed my socket loses connection
and throws an error- I need to close it after the error so it can listen
for another connection.)

On the Finally is where you would check for open status and close it if it
is open. There should be an enum concerning an open status condition for
things like files, SQL Server connections, etc, ect, where you ask the
question. Are you open?

You would also do this Are you open? check at the Catch before the Exception
thrown, because you're never going to reach the Finally in that condition.

Some people only use a Try/Catch, because what code is after the Try/Catch
is a final code execution before the routine is exited, good or bad.
 
Back
Top