The problem with Try Catch Finally...

Ask a Question related to ASP.NET General, Design and Development.

  1. #1

    Default The problem with Try Catch Finally...

    Variable scope doesn't make sense to me when it comes to Try Catch Finally.

    Example: In order to close/dispose a db connection you have to dim the
    connection outside of the Try Catch Finally block. But, I prefer to dim them
    "on the fly" only if needed (save as much resources as possible). A little
    further... I may wish to create a sqlcommand and datareader object ONLY if
    certain conditions are met. But, if I want to clean these up in the Finally
    then I am FORCED to declare them above the Try.

    Why???


    VB Programmer Guest

  2. Similar Questions and Discussions

    1. [PHP-DEV] finally again
      > IMHO, I think that replicating the finally code at the end of every catch My mistake, it's not necessary to replicate the code at the end of every...
    2. Question: Try,Catch,Finally
      I usually put my declarations for db connections, datasets, datareaders, etc... above the Try portion. Inside the Try is where I open my...
    3. [PHP-DEV] try/catch/FINALLY
      Please, ignore this: exit And read this instead: IMHO I think that an implementation start would be hooking the exit of the try statement even...
    4. Re[2]: [PHP-DEV] try/catch/FINALLY
      Hello Marcus, Wednesday, August 6, 2003, 1:14:10 PM, you wrote: CD>> What about finally ? MB> There's absolute no need for finally: MB>...
    5. [PHP-DEV] try/catch/FINALLY
      Hi all, I know there was a lot of discussion about try/catch, but I will bring it up again: What about finally ? I know someone posted that...
  3. #2

    Default Re: The problem with Try Catch Finally...

    Why not declare them and just CREATE them when you need to. After all,
    that's what may take the longest.

    - Jeff

    "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    news:#$uYXPNYDHA.1004@TK2MSFTNGP12.phx.gbl...
    > Variable scope doesn't make sense to me when it comes to Try Catch
    Finally.
    >
    > Example: In order to close/dispose a db connection you have to dim the
    > connection outside of the Try Catch Finally block. But, I prefer to dim
    them
    > "on the fly" only if needed (save as much resources as possible). A little
    > further... I may wish to create a sqlcommand and datareader object ONLY if
    > certain conditions are met. But, if I want to clean these up in the
    Finally
    > then I am FORCED to declare them above the Try.
    >
    > Why???
    >
    >

    Jeff Voigt Guest

  4. #3

    Default Re: The problem with Try Catch Finally...

    Well, you are most of the way there in your description. Variables are local
    to the scope they are declared in, and scope is determined by code block.
    Any time you have a code block, you can declare local variables in that
    block. This is true for try - catch - finally, if, while, or anything other
    similar construct. This enables you to declare a new variable inside that
    block, and have it marked for GC once you exit that code block.

    What it means for you in terms of your try - catch is that you need to code
    around how you create it. First of all, declaring a variable doesn't
    allocate space for it, so you don't have to worry about that. You may also
    want to re-think what you are enclosing in a try-catch block. You don't need
    to wrap huge chuck of code in such a block - you just need to wrap a
    dangerous operation that might throw an exception in such a block. So,
    declare, prepare, then when you execute the risky operation, wrap it in a
    try-catch. I seldom have more than a couple of lines of code in a try block,
    and usually have exactly one.

    --
    Chris Jackson
    Software Engineer
    Microsoft MVP - Windows XP
    Windows XP Associate Expert
    --
    "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    news:%23$uYXPNYDHA.1004@TK2MSFTNGP12.phx.gbl...
    > Variable scope doesn't make sense to me when it comes to Try Catch
    Finally.
    >
    > Example: In order to close/dispose a db connection you have to dim the
    > connection outside of the Try Catch Finally block. But, I prefer to dim
    them
    > "on the fly" only if needed (save as much resources as possible). A little
    > further... I may wish to create a sqlcommand and datareader object ONLY if
    > certain conditions are met. But, if I want to clean these up in the
    Finally
    > then I am FORCED to declare them above the Try.
    >
    > Why???
    >
    >

    Chris Jackson Guest

  5. #4

    Default Re: The problem with Try Catch Finally...

    > You mentioned "I seldom have more than a couple of lines of code in a try
    > block, and usually have exactly one." Is this standard? In VB6 I've
    always

    No, that is not the standard. I, for example, will put all of the code in a
    method inside a try/catch block, and then put additional try/catch blocks
    and conditional code inside that outer block to catch specific errors. The
    outside one is for anything I might have missed. How you use it is up to
    you, and what your needs are.
    > What is considered "risky operation"? Connecting to db, filling datasets,
    > datareaders, etc...?
    That's a difficult question to answer (which is why I wrap all of my method
    code in an outer try/catch block). Any operation which might cause your
    program to malfunction is risky.

    The bottom line is (and everyone here seems to agree on this), declare your
    variables outside of the block, and assign them inside the block.

    --
    HTH,

    Kevin Spencer
    Microsoft MVP
    ..Net Developer
    [url]http://www.takempis.com[/url]
    Complex things are made up of
    lots of simple things.


    "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    news:%23CDhv$NYDHA.1744@TK2MSFTNGP12.phx.gbl...
    > Very interesting response.
    >
    > You mentioned "I seldom have more than a couple of lines of code in a try
    > block, and usually have exactly one." Is this standard? In VB6 I've
    always
    > coded using "On Error Goto errHandler, etc..." which wraps all the code
    into
    > the trap. Do I have to need a paradigm shift? How do I handle errors
    > outside of the Try statement?
    >
    > What is considered "risky operation"? Connecting to db, filling datasets,
    > datareaders, etc...?
    >
    > "Chris Jackson" <chrisj@mvps.org> wrote in message
    > news:eketxiNYDHA.384@TK2MSFTNGP12.phx.gbl...
    > > Well, you are most of the way there in your description. Variables are
    > local
    > > to the scope they are declared in, and scope is determined by code
    block.
    > > Any time you have a code block, you can declare local variables in that
    > > block. This is true for try - catch - finally, if, while, or anything
    > other
    > > similar construct. This enables you to declare a new variable inside
    that
    > > block, and have it marked for GC once you exit that code block.
    > >
    > > What it means for you in terms of your try - catch is that you need to
    > code
    > > around how you create it. First of all, declaring a variable doesn't
    > > allocate space for it, so you don't have to worry about that. You may
    also
    > > want to re-think what you are enclosing in a try-catch block. You don't
    > need
    > > to wrap huge chuck of code in such a block - you just need to wrap a
    > > dangerous operation that might throw an exception in such a block. So,
    > > declare, prepare, then when you execute the risky operation, wrap it in
    a
    > > try-catch. I seldom have more than a couple of lines of code in a try
    > block,
    > > and usually have exactly one.
    > >
    > > --
    > > Chris Jackson
    > > Software Engineer
    > > Microsoft MVP - Windows XP
    > > Windows XP Associate Expert
    > > --
    > > "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    > > news:%23$uYXPNYDHA.1004@TK2MSFTNGP12.phx.gbl...
    > > > Variable scope doesn't make sense to me when it comes to Try Catch
    > > Finally.
    > > >
    > > > Example: In order to close/dispose a db connection you have to dim the
    > > > connection outside of the Try Catch Finally block. But, I prefer to
    dim
    > > them
    > > > "on the fly" only if needed (save as much resources as possible). A
    > little
    > > > further... I may wish to create a sqlcommand and datareader object
    ONLY
    > if
    > > > certain conditions are met. But, if I want to clean these up in the
    > > Finally
    > > > then I am FORCED to declare them above the Try.
    > > >
    > > > Why???
    > > >
    > > >
    > >
    > >
    >
    >

    Kevin Spencer Guest

  6. #5

    Default Re: The problem with Try Catch Finally...

    And one other thing I should mention, in case you don't understand. The
    problem you experienced was due to referencing variables declared inside the
    try/catch block from the Finally block. The Finally block executes
    regardless of whether an error occurs or not. That means that it must be
    able to access the variables used in it regardless of whether they were
    assigned or not. When you declare a variable inside the try block, your code
    might never reach the declaration before execution falls through to the
    catch block. Therefore, any variable referenced in the Finnally block must
    be declared prior to the Try block.

    --
    HTH,

    Kevin Spencer
    Microsoft MVP
    ..Net Developer
    [url]http://www.takempis.com[/url]
    Complex things are made up of
    lots of simple things.

    "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    news:%23CDhv$NYDHA.1744@TK2MSFTNGP12.phx.gbl...
    > Very interesting response.
    >
    > You mentioned "I seldom have more than a couple of lines of code in a try
    > block, and usually have exactly one." Is this standard? In VB6 I've
    always
    > coded using "On Error Goto errHandler, etc..." which wraps all the code
    into
    > the trap. Do I have to need a paradigm shift? How do I handle errors
    > outside of the Try statement?
    >
    > What is considered "risky operation"? Connecting to db, filling datasets,
    > datareaders, etc...?
    >
    > "Chris Jackson" <chrisj@mvps.org> wrote in message
    > news:eketxiNYDHA.384@TK2MSFTNGP12.phx.gbl...
    > > Well, you are most of the way there in your description. Variables are
    > local
    > > to the scope they are declared in, and scope is determined by code
    block.
    > > Any time you have a code block, you can declare local variables in that
    > > block. This is true for try - catch - finally, if, while, or anything
    > other
    > > similar construct. This enables you to declare a new variable inside
    that
    > > block, and have it marked for GC once you exit that code block.
    > >
    > > What it means for you in terms of your try - catch is that you need to
    > code
    > > around how you create it. First of all, declaring a variable doesn't
    > > allocate space for it, so you don't have to worry about that. You may
    also
    > > want to re-think what you are enclosing in a try-catch block. You don't
    > need
    > > to wrap huge chuck of code in such a block - you just need to wrap a
    > > dangerous operation that might throw an exception in such a block. So,
    > > declare, prepare, then when you execute the risky operation, wrap it in
    a
    > > try-catch. I seldom have more than a couple of lines of code in a try
    > block,
    > > and usually have exactly one.
    > >
    > > --
    > > Chris Jackson
    > > Software Engineer
    > > Microsoft MVP - Windows XP
    > > Windows XP Associate Expert
    > > --
    > > "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    > > news:%23$uYXPNYDHA.1004@TK2MSFTNGP12.phx.gbl...
    > > > Variable scope doesn't make sense to me when it comes to Try Catch
    > > Finally.
    > > >
    > > > Example: In order to close/dispose a db connection you have to dim the
    > > > connection outside of the Try Catch Finally block. But, I prefer to
    dim
    > > them
    > > > "on the fly" only if needed (save as much resources as possible). A
    > little
    > > > further... I may wish to create a sqlcommand and datareader object
    ONLY
    > if
    > > > certain conditions are met. But, if I want to clean these up in the
    > > Finally
    > > > then I am FORCED to declare them above the Try.
    > > >
    > > > Why???
    > > >
    > > >
    > >
    > >
    >
    >

    Kevin Spencer Guest

  7. #6

    Default Re: The problem with Try Catch Finally...

    Folks, I cant beleive how long this thread has become !

    When we are old and grey, we can enchant our grandchildren with stories of
    how we spent our precious youth talking about Try Catch blocks !

    Sorry, couldnt resist that, keep smiling :)





    "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    news:%23$uYXPNYDHA.1004@TK2MSFTNGP12.phx.gbl...
    > Variable scope doesn't make sense to me when it comes to Try Catch
    Finally.
    >
    > Example: In order to close/dispose a db connection you have to dim the
    > connection outside of the Try Catch Finally block. But, I prefer to dim
    them
    > "on the fly" only if needed (save as much resources as possible). A little
    > further... I may wish to create a sqlcommand and datareader object ONLY if
    > certain conditions are met. But, if I want to clean these up in the
    Finally
    > then I am FORCED to declare them above the Try.
    >
    > Why???
    >
    >

    Terry Burns Guest

  8. #7

    Default Re: The problem with Try Catch Finally...

    Good stuff! :)

    "Terry Burns" <terry_burns@BTOpenworld.com> wrote in message
    news:OX6i9rOYDHA.1816@TK2MSFTNGP09.phx.gbl...
    > Folks, I cant beleive how long this thread has become !
    >
    > When we are old and grey, we can enchant our grandchildren with stories of
    > how we spent our precious youth talking about Try Catch blocks !
    >
    > Sorry, couldnt resist that, keep smiling :)
    >
    >
    >
    >
    >
    > "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    > news:%23$uYXPNYDHA.1004@TK2MSFTNGP12.phx.gbl...
    > > Variable scope doesn't make sense to me when it comes to Try Catch
    > Finally.
    > >
    > > Example: In order to close/dispose a db connection you have to dim the
    > > connection outside of the Try Catch Finally block. But, I prefer to dim
    > them
    > > "on the fly" only if needed (save as much resources as possible). A
    little
    > > further... I may wish to create a sqlcommand and datareader object ONLY
    if
    > > certain conditions are met. But, if I want to clean these up in the
    > Finally
    > > then I am FORCED to declare them above the Try.
    > >
    > > Why???
    > >
    > >
    >
    >

    VB Programmer Guest

  9. #8

    Default Re: The problem with Try Catch Finally...

    > > You mentioned "I seldom have more than a couple of lines of code in a
    try
    > > block, and usually have exactly one." Is this standard? In VB6 I've
    > always
    > No, that is not the standard. I, for example, will put all of the code in
    a
    > method inside a try/catch block, and then put additional try/catch blocks
    > and conditional code inside that outer block to catch specific errors. The
    > outside one is for anything I might have missed. How you use it is up to
    > you, and what your needs are.
    I would never go so far as to put all of the code inside of a method inside
    of a try-catch block, because then you are never really sure what you are
    catching. Sure, you could simply catch a System.Exception, but if you don't
    know what you're catching, and as a result can't react appropriately, you
    probably don't want to just sit on that error instead of passing it up
    through the call stack.

    With VB6, you just had to universally set up an onerror statement that
    caught all errors, and then go through and figure out what happened and what
    to do about it. The beauty of try-catch is that you can wrap specific
    statements and handle it appropriately.

    Let's do an example - open up a SQL Server connection, set up a command
    object, and execute that command object:

    ----
    SqlConnection connMyConnection = new SqlConnection(szConnectionString);
    SqlCommand cmdMyCommand = new SqlCommand("MyCommand", connMyConnection);
    cmdMyCommand .CommandType = CommandType.StoredProcedure;
    cmdMyCommand .Parameters.Add("@myParameter", SqlDbType.VarChar, 50).Value =
    szValue;
    connMyConnection.Open();
    cmdMyCommand.ExecuteNonQuery();
    ----

    The SqlConnection constructor that I used does not throw an exception, so
    there is nothing to catch there.
    The SqlCommand constructor that I used does not throw an exception, so there
    is nothing to catch there.
    Setting the command type could throw an ArgumentException, so you'll want to
    catch that.
    The add method of the parameters collection doesn't throw an exception, nor
    does the Value property of the SqlParameter object, so there is nothing to
    catch there.
    The Open method of SqlConnection could throw either an
    InvalidOperationException or a SqlException, so you'll want to catch that.
    The ExecuteNonQuery method of SqlCommand could throw a SqlException, so
    you'll want to catch that.

    So, you end up with:

    ----
    SqlConnection connMyConnection = new SqlConnection(connectionString);
    SqlCommand cmdMyCommand = new SqlCommand("MyCommand", connMyConnection);
    try {
    cmdMyCommand .CommandType = CommandType.StoredProcedure;
    } catch (ArgumentException myArgumentException) {
    // do something to react to this - since it's hard coded, you can
    probably fix your code and get rid of this check
    } finally {
    // do some cleanup work
    }
    cmdMyCommand .Parameters.Add("@myParameter", SqlDbType.VarChar, 50).Value =
    szValue;
    try {
    connMyConnection.Open();
    } catch (InvalidOperationException myInvalidOperationException) {
    // do something to react to this - since it's hard coded, again you can
    probably fix your code and dispense with this check
    } catch (SqlException mySqlException1) {
    // do something to react to this - either dump to the event log or, if
    in debug mode (use preprocessors) write back the message
    } finally {
    // do some cleanup work
    }
    try {
    cmdMyCommand.ExecuteNonQuery();
    } catch (SqlException mySqlException2) {
    // do something to react to this - either dump to the event log or, if
    in debug mode (use preprocessors) write back the message
    } finally {
    // do some cleanup work
    }
    ----

    If you look up the best practices, you will find it stated in as many words:

    "Use try/finally blocks around code that can potentially generate an
    exception and centralize your catch statements in one location. In this way,
    the try statement generates the exception, the finally statement closes or
    deallocates resources, and the catch statement handles the exception from a
    central location."

    Full list of best practices here:

    [url]http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconbestpracticesforhandlingexceptions.asp[/url]

    So yes, I would beg to differ. I do consider this a standard. It's what I've
    been doing in C++ for years now.

    Also, you can check for exceptions before they are thrown. If you are going
    to close the aforementioned SqlConnection, instead of just using:

    connMyConnection.Close();

    use:

    if (connMyConnection != null && connMyConnection.State !=
    ConnectionState.Closed) {
    connMyConnection.Close();
    }

    And so it goes.


    --
    Chris Jackson
    Software Engineer
    Microsoft MVP - Windows XP
    Windows XP Associate Expert
    --


    Chris Jackson Guest

  10. #9

    Default Re: The problem with Try Catch Finally...

    A risky operation is anything that could raise an exception. When calling a
    method check the help on it. It will list any exceptions that it raised and
    the conditions to cause the exception.

    Anytime a risky operation is called place it in the try block, and in the
    finally block clean up any resources such as filestreams, database
    connections, references to COM objects, etc... In the catch block you
    could...

    1) propagate the error to the caller
    2) wrap that error in a new custom (InnerException) error of your own giving
    a more human understandable message and throw to caller
    3) log the error and continue with rest of method
    4) ignore and do again (entire try-catch-finally in a loop).
    5) ignore the error and continue with rest of method.
    6) ?? anything you desire

    What you do depends on the needs/requirements of your application.

    --
    Michael Lang, MCSD
    See my .NET open source projects
    [url]http://sourceforge.net/projects/dbobjecter[/url] (code generator)
    [url]http://sourceforge.net/projects/genadonet[/url] ("generic" ADO.NET)

    "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    news:%23CDhv$NYDHA.1744@TK2MSFTNGP12.phx.gbl...
    > Very interesting response.
    >
    > You mentioned "I seldom have more than a couple of lines of code in a try
    > block, and usually have exactly one." Is this standard? In VB6 I've
    always
    > coded using "On Error Goto errHandler, etc..." which wraps all the code
    into
    > the trap. Do I have to need a paradigm shift? How do I handle errors
    > outside of the Try statement?
    >
    > What is considered "risky operation"? Connecting to db, filling datasets,
    > datareaders, etc...?
    >
    > "Chris Jackson" <chrisj@mvps.org> wrote in message
    > news:eketxiNYDHA.384@TK2MSFTNGP12.phx.gbl...
    > > Well, you are most of the way there in your description. Variables are
    > local
    > > to the scope they are declared in, and scope is determined by code
    block.
    > > Any time you have a code block, you can declare local variables in that
    > > block. This is true for try - catch - finally, if, while, or anything
    > other
    > > similar construct. This enables you to declare a new variable inside
    that
    > > block, and have it marked for GC once you exit that code block.
    > >
    > > What it means for you in terms of your try - catch is that you need to
    > code
    > > around how you create it. First of all, declaring a variable doesn't
    > > allocate space for it, so you don't have to worry about that. You may
    also
    > > want to re-think what you are enclosing in a try-catch block. You don't
    > need
    > > to wrap huge chuck of code in such a block - you just need to wrap a
    > > dangerous operation that might throw an exception in such a block. So,
    > > declare, prepare, then when you execute the risky operation, wrap it in
    a
    > > try-catch. I seldom have more than a couple of lines of code in a try
    > block,
    > > and usually have exactly one.
    > >
    > > --
    > > Chris Jackson
    > > Software Engineer
    > > Microsoft MVP - Windows XP
    > > Windows XP Associate Expert
    > > --
    > > "VB Programmer" <growNO-SPAM@go-intech.com> wrote in message
    > > news:%23$uYXPNYDHA.1004@TK2MSFTNGP12.phx.gbl...
    > > > Variable scope doesn't make sense to me when it comes to Try Catch
    > > Finally.
    > > >
    > > > Example: In order to close/dispose a db connection you have to dim the
    > > > connection outside of the Try Catch Finally block. But, I prefer to
    dim
    > > them
    > > > "on the fly" only if needed (save as much resources as possible). A
    > little
    > > > further... I may wish to create a sqlcommand and datareader object
    ONLY
    > if
    > > > certain conditions are met. But, if I want to clean these up in the
    > > Finally
    > > > then I am FORCED to declare them above the Try.
    > > >
    > > > Why???
    > > >
    > > >
    > >
    > >
    >
    >

    Michael Lang Guest

  11. #10

    Default Re: The problem with Try Catch Finally...

    > I would never go so far as to put all of the code inside of a method
    inside
    > of a try-catch block, because then you are never really sure what you are
    > catching. Sure, you could simply catch a System.Exception, but if you
    don't
    > know what you're catching, and as a result can't react appropriately, you
    > probably don't want to just sit on that error instead of passing it up
    > through the call stack.
    >
    I'm always sure of what I'm catching, because I use a global error-handler
    routine in my outer try/catch block, which logs the Exception message, any
    InnerException message, and a Stack trace to the Event Log. This is so that
    I can figure out what caused the error and determine how to best handle it
    with code.

    --
    HTH,

    Kevin Spencer
    Microsoft MVP
    ..Net Developer
    [url]http://www.takempis.com[/url]
    Complex things are made up of
    lots of simple things.

    "Chris Jackson" <chrisj@mvps.org> wrote in message
    news:uJBmw9PYDHA.2284@TK2MSFTNGP12.phx.gbl...
    > > > You mentioned "I seldom have more than a couple of lines of code in a
    > try
    > > > block, and usually have exactly one." Is this standard? In VB6 I've
    > > always
    > > No, that is not the standard. I, for example, will put all of the code
    in
    > a
    > > method inside a try/catch block, and then put additional try/catch
    blocks
    > > and conditional code inside that outer block to catch specific errors.
    The
    > > outside one is for anything I might have missed. How you use it is up to
    > > you, and what your needs are.
    >
    > I would never go so far as to put all of the code inside of a method
    inside
    > of a try-catch block, because then you are never really sure what you are
    > catching. Sure, you could simply catch a System.Exception, but if you
    don't
    > know what you're catching, and as a result can't react appropriately, you
    > probably don't want to just sit on that error instead of passing it up
    > through the call stack.
    >
    > With VB6, you just had to universally set up an onerror statement that
    > caught all errors, and then go through and figure out what happened and
    what
    > to do about it. The beauty of try-catch is that you can wrap specific
    > statements and handle it appropriately.
    >
    > Let's do an example - open up a SQL Server connection, set up a command
    > object, and execute that command object:
    >
    > ----
    > SqlConnection connMyConnection = new SqlConnection(szConnectionString);
    > SqlCommand cmdMyCommand = new SqlCommand("MyCommand", connMyConnection);
    > cmdMyCommand .CommandType = CommandType.StoredProcedure;
    > cmdMyCommand .Parameters.Add("@myParameter", SqlDbType.VarChar, 50).Value
    =
    > szValue;
    > connMyConnection.Open();
    > cmdMyCommand.ExecuteNonQuery();
    > ----
    >
    > The SqlConnection constructor that I used does not throw an exception, so
    > there is nothing to catch there.
    > The SqlCommand constructor that I used does not throw an exception, so
    there
    > is nothing to catch there.
    > Setting the command type could throw an ArgumentException, so you'll want
    to
    > catch that.
    > The add method of the parameters collection doesn't throw an exception,
    nor
    > does the Value property of the SqlParameter object, so there is nothing to
    > catch there.
    > The Open method of SqlConnection could throw either an
    > InvalidOperationException or a SqlException, so you'll want to catch that.
    > The ExecuteNonQuery method of SqlCommand could throw a SqlException, so
    > you'll want to catch that.
    >
    > So, you end up with:
    >
    > ----
    > SqlConnection connMyConnection = new SqlConnection(connectionString);
    > SqlCommand cmdMyCommand = new SqlCommand("MyCommand", connMyConnection);
    > try {
    > cmdMyCommand .CommandType = CommandType.StoredProcedure;
    > } catch (ArgumentException myArgumentException) {
    > // do something to react to this - since it's hard coded, you can
    > probably fix your code and get rid of this check
    > } finally {
    > // do some cleanup work
    > }
    > cmdMyCommand .Parameters.Add("@myParameter", SqlDbType.VarChar, 50).Value
    =
    > szValue;
    > try {
    > connMyConnection.Open();
    > } catch (InvalidOperationException myInvalidOperationException) {
    > // do something to react to this - since it's hard coded, again you
    can
    > probably fix your code and dispense with this check
    > } catch (SqlException mySqlException1) {
    > // do something to react to this - either dump to the event log or, if
    > in debug mode (use preprocessors) write back the message
    > } finally {
    > // do some cleanup work
    > }
    > try {
    > cmdMyCommand.ExecuteNonQuery();
    > } catch (SqlException mySqlException2) {
    > // do something to react to this - either dump to the event log or, if
    > in debug mode (use preprocessors) write back the message
    > } finally {
    > // do some cleanup work
    > }
    > ----
    >
    > If you look up the best practices, you will find it stated in as many
    words:
    >
    > "Use try/finally blocks around code that can potentially generate an
    > exception and centralize your catch statements in one location. In this
    way,
    > the try statement generates the exception, the finally statement closes or
    > deallocates resources, and the catch statement handles the exception from
    a
    > central location."
    >
    > Full list of best practices here:
    >
    >
    [url]http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconbestpracticesforhandlingexceptions.asp[/url]
    >
    > So yes, I would beg to differ. I do consider this a standard. It's what
    I've
    > been doing in C++ for years now.
    >
    > Also, you can check for exceptions before they are thrown. If you are
    going
    > to close the aforementioned SqlConnection, instead of just using:
    >
    > connMyConnection.Close();
    >
    > use:
    >
    > if (connMyConnection != null && connMyConnection.State !=
    > ConnectionState.Closed) {
    > connMyConnection.Close();
    > }
    >
    > And so it goes.
    >
    >
    > --
    > Chris Jackson
    > Software Engineer
    > Microsoft MVP - Windows XP
    > Windows XP Associate Expert
    > --
    >
    >

    Kevin Spencer Guest

Posting Permissions

  • You may not post new threads
  • You may post replies
  • You may not post attachments
  • You may not edit your posts

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139