c# - How to test statements individually rather than a block of code using Try-Catch? -


the code below fail because bind() called on socket has not been "prepared", though there code prepare socket. code prepares socket out of scope (another try block).

        // prepare socket         try         {             socket = new socket(endpoint.addressfamily, sockettype.stream, protocoltype.tcp);         }         catch (exception e)         {             log.write("socket preparation failed");         }                 {             if (socket != null)             {                 socket.shutdown(socketshutdown.both);                 socket.close();             }         }          // bind         try         {             socket.bind(endpoint);         }            catch (exception e)         {             log.write("bind() failed");         }                 {             if (socket != null)             {                 socket.shutdown(socketshutdown.both);                 socket.close();             }         }          // enable listening         try         {             socket.listen(1000);         }         catch (exception e)         {             log.write("listen() failed");         }                 {             if (socket != null)             {                 socket.shutdown(socketshutdown.both);                 socket.close();             }         } 

here's 1 way write it. finally part of outer scope, while catches in inner scope. i'm throwing after each catch, can handle differently.

note each finally clause executed it's corresponding try clause falls out of scope, not when method exists.

    socket socket;      try     {         // prepare socket         try         {             socket = new socket(endpoint.addressfamily, sockettype.stream, protocoltype.tcp);         }         catch         {             log.write("socket preparation failed");             throw;         }          // bind         try         {             socket.bind(endpoint);         }            catch         {             log.write("bind() failed");             throw;         }          // enable listening         try         {             socket.listen(1000);         }         catch         {             log.write("listen() failed");             throw;         }     }         {         if (socket != null)         {             socket.shutdown(socketshutdown.both);             socket.close();         }     } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -