Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. a try inside another

a try inside another

Scheduled Pinned Locked Moved C#
help
38 Posts 15 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Pete OHanlon

    Rick van Woudenberg wrote:

    But what's the use of a try block without a catch block.

    To ensure that the exception gets thrown up the chain, AND some critical piece of code gets executed. Consider this example:

    private void DoSomething()
    {
    SqlConnection connection = null;
    try
    {
    connection = new SqlConnection();
    // Do something that might cause an exception...
    }
    finally
    {
    if (connection.ConnectionState == ConnectionState.Open)
    connection.Close();
    }
    }

    BTW, try/finally is exactly how the using statement is implemented for auto-disposable behaviour.

    Forgive your enemies - it messes with their heads

    My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

    R Offline
    R Offline
    Rick van Woudenberg
    wrote on last edited by
    #10

    Pete, Good point. I guess you're sample is way better than I used to do it. ( see code below ). Other than the obvious thread freezing and just the fact that handling exceptions are 'expensive'.

    private void DoSomething()
    {
    SqlConnection connection = null;
    try
    {
    connection = new SqlConnection();
    // Do something that might cause an exception...
    connection.Open();
    }
    catch
    {
    MessageBox.Show("Connecting to the database failed..");
    }

    if (connection.ConnectionState == ConnectionState.Open)
    connection.Close();
    }

    J 1 Reply Last reply
    0
    • A Ali Al Omairi Abu AlHassan

      this will hide the inner exception of the inner try?

      Help people,so poeple can help you.

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #11

      the finally block is always executed, and any exception that gets thrown will be caught by the first surrounding and matching catch block. So the finally block will execute first (unless the catch belongs to the same try as the finally). :)

      Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum

      Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

      1 Reply Last reply
      0
      • R Rick van Woudenberg

        Pete, Good point. I guess you're sample is way better than I used to do it. ( see code below ). Other than the obvious thread freezing and just the fact that handling exceptions are 'expensive'.

        private void DoSomething()
        {
        SqlConnection connection = null;
        try
        {
        connection = new SqlConnection();
        // Do something that might cause an exception...
        connection.Open();
        }
        catch
        {
        MessageBox.Show("Connecting to the database failed..");
        }

        if (connection.ConnectionState == ConnectionState.Open)
        connection.Close();
        }

        J Offline
        J Offline
        J4amieC
        wrote on last edited by
        #12

        That code example made me shudder. Separation of concerns; Is the concern database access or User notification, because it sure as hell shouldnt be both.

        R 1 Reply Last reply
        0
        • A Ali Al Omairi Abu AlHassan

          guys; I was exminning some code and i found this:

          try
          {
              try
              {
                  ...
              }
              finally
              {
                  ...
              }
          }
          catch
          {
              throw;
          }
          

          I am wondering if this is legal. I mean catch anything and trow anything; or maybe it's usefull for something. because the developer who write this code is someone i believe he is an expert. Thank you;

          Help people,so poeple can help you.

          P Offline
          P Offline
          PIEBALDconsult
          wrote on last edited by
          #13

          The outer try/catch in this example is pointless, remove it. If the catch in the outer try/catch actually does something (like log the Exception), then the inner try/finally should be removed and the finally moved out to make the try/catch into a try/catch/finally. Nested try/catches (while sometimes necessary) are a code smell and should be investigated thoroughly. (Or Thoreau[^]ly -- simplify simplify.)

          L J 2 Replies Last reply
          0
          • P PIEBALDconsult

            The outer try/catch in this example is pointless, remove it. If the catch in the outer try/catch actually does something (like log the Exception), then the inner try/finally should be removed and the finally moved out to make the try/catch into a try/catch/finally. Nested try/catches (while sometimes necessary) are a code smell and should be investigated thoroughly. (Or Thoreau[^]ly -- simplify simplify.)

            L Offline
            L Offline
            Luc Pattyn
            wrote on last edited by
            #14

            PIEBALDconsult wrote:

            If the catch in the outer try/catch actually does something (like log the Exception), then the inner try/finally should be removed and the finally moved out to make the try/catch into a try/catch/finally.

            If the catch in the outer try/catch actually does something, then your suggestion would change what happens to exceptions thrown by the finally block itself. :)

            Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum

            Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

            P 1 Reply Last reply
            0
            • P Pete OHanlon

              Rick van Woudenberg wrote:

              But what's the use of a try block without a catch block.

              To ensure that the exception gets thrown up the chain, AND some critical piece of code gets executed. Consider this example:

              private void DoSomething()
              {
              SqlConnection connection = null;
              try
              {
              connection = new SqlConnection();
              // Do something that might cause an exception...
              }
              finally
              {
              if (connection.ConnectionState == ConnectionState.Open)
              connection.Close();
              }
              }

              BTW, try/finally is exactly how the using statement is implemented for auto-disposable behaviour.

              Forgive your enemies - it messes with their heads

              My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

              V Offline
              V Offline
              V 0
              wrote on last edited by
              #15

              Suppose the line

              connection = new SqlConnection();

              fails and connection stays null. Won't you receive a very ugly "unhandled exception" message? (haven't tried it).

              V.

              P 1 Reply Last reply
              0
              • V V 0

                Suppose the line

                connection = new SqlConnection();

                fails and connection stays null. Won't you receive a very ugly "unhandled exception" message? (haven't tried it).

                V.

                P Offline
                P Offline
                Pete OHanlon
                wrote on last edited by
                #16

                You will, but the exception will bubble up (actually, in this case you won't get an exception. The zero parameter constructor doesn't do anything that can cause an exception). I deliberately didn't put exception handling in here to avoid clouding the issue.

                Forgive your enemies - it messes with their heads

                My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                1 Reply Last reply
                0
                • J J4amieC

                  That code example made me shudder. Separation of concerns; Is the concern database access or User notification, because it sure as hell shouldnt be both.

                  R Offline
                  R Offline
                  Rick van Woudenberg
                  wrote on last edited by
                  #17

                  Well, as far as I'm concerned both would be nice. Sure, the connection to the database has priority over user notification, however when something stuffs up, I generally let the user know. In that particular case I would do something like :

                  private void DoSomething()
                  {
                  SqlConnection connection = null;
                  try
                  {
                  connection = new SqlConnection();
                  // Do something that might cause an exception...
                  connection.Open();
                  }
                  catch(SqlException ex)
                  {
                  MessageBox.Show(ex.ToString(); // or something else to notify the customer
                  }
                  finally
                  {
                  if (connection.ConnectionState == ConnectionState.Open)
                  connection.Close();
                  }
                  }

                  Then you actually have both of two worlds. However, that puts us right back to the essence of this discussion. Having a catch clause in a method is not something to be ashamed of, though I get the feeling that many developers think that way.

                  J D 2 Replies Last reply
                  0
                  • R Rick van Woudenberg

                    Well, as far as I'm concerned both would be nice. Sure, the connection to the database has priority over user notification, however when something stuffs up, I generally let the user know. In that particular case I would do something like :

                    private void DoSomething()
                    {
                    SqlConnection connection = null;
                    try
                    {
                    connection = new SqlConnection();
                    // Do something that might cause an exception...
                    connection.Open();
                    }
                    catch(SqlException ex)
                    {
                    MessageBox.Show(ex.ToString(); // or something else to notify the customer
                    }
                    finally
                    {
                    if (connection.ConnectionState == ConnectionState.Open)
                    connection.Close();
                    }
                    }

                    Then you actually have both of two worlds. However, that puts us right back to the essence of this discussion. Having a catch clause in a method is not something to be ashamed of, though I get the feeling that many developers think that way.

                    J Offline
                    J Offline
                    J4amieC
                    wrote on last edited by
                    #18

                    ahhh, no no no. If your UI code is mixed with your database access code; you're doing it wrong If you show Exception messages unsanitized to your users; you're doing it wrong

                    B R G 3 Replies Last reply
                    0
                    • J J4amieC

                      ahhh, no no no. If your UI code is mixed with your database access code; you're doing it wrong If you show Exception messages unsanitized to your users; you're doing it wrong

                      B Offline
                      B Offline
                      BobJanova
                      wrote on last edited by
                      #19

                      Totally agreed on the first point. But regarding the second, he did mention that he might put something else there. I tend to have something which shows them the exception trace in the critical exception handler, because if there is a serious bug, you (the developer) want that information to fix it. In the case of a database connection failure, though, definitely not, because most of those reasons are not because your software is broken.

                      J 1 Reply Last reply
                      0
                      • B BobJanova

                        Totally agreed on the first point. But regarding the second, he did mention that he might put something else there. I tend to have something which shows them the exception trace in the critical exception handler, because if there is a serious bug, you (the developer) want that information to fix it. In the case of a database connection failure, though, definitely not, because most of those reasons are not because your software is broken.

                        J Offline
                        J Offline
                        J4amieC
                        wrote on last edited by
                        #20

                        BobJanova wrote:

                        you (the developer) want that information to fix it

                        And therein is the point. I want it, but I dont EVER want a user to see it. This is what the Windows Event Log (or, perhaps another type of log) is for. You never have a reason to show a user an unsanitized exception message (caveat: they're programmers and can actually act on the information). There is the potential to give away sensitive information if you do so.

                        P 1 Reply Last reply
                        0
                        • J J4amieC

                          BobJanova wrote:

                          you (the developer) want that information to fix it

                          And therein is the point. I want it, but I dont EVER want a user to see it. This is what the Windows Event Log (or, perhaps another type of log) is for. You never have a reason to show a user an unsanitized exception message (caveat: they're programmers and can actually act on the information). There is the potential to give away sensitive information if you do so.

                          P Offline
                          P Offline
                          Pete OHanlon
                          wrote on last edited by
                          #21

                          J4amieC wrote:

                          This is what the Windows Event Log (or, perhaps another type of log) is for.

                          Or to put it another way - that's what log4net is for. :-D

                          Forgive your enemies - it messes with their heads

                          My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                          1 Reply Last reply
                          0
                          • L Luc Pattyn

                            PIEBALDconsult wrote:

                            If the catch in the outer try/catch actually does something (like log the Exception), then the inner try/finally should be removed and the finally moved out to make the try/catch into a try/catch/finally.

                            If the catch in the outer try/catch actually does something, then your suggestion would change what happens to exceptions thrown by the finally block itself. :)

                            Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum

                            Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

                            P Offline
                            P Offline
                            PIEBALDconsult
                            wrote on last edited by
                            #22

                            Luc Pattyn wrote:

                            exceptions thrown by the finally block itself.

                            Of which there are none. or put a try/catch in the finally. :-D

                            L 1 Reply Last reply
                            0
                            • P PIEBALDconsult

                              Luc Pattyn wrote:

                              exceptions thrown by the finally block itself.

                              Of which there are none. or put a try/catch in the finally. :-D

                              L Offline
                              L Offline
                              Luc Pattyn
                              wrote on last edited by
                              #23

                              PIEBALDconsult wrote:

                              Of which there are none

                              Of course there are, that is exactly what the three dots are standing for. You can't escape nested try constructs if it has to be fool proof... :)

                              Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum

                              Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

                              P 1 Reply Last reply
                              0
                              • L Luc Pattyn

                                PIEBALDconsult wrote:

                                Of which there are none

                                Of course there are, that is exactly what the three dots are standing for. You can't escape nested try constructs if it has to be fool proof... :)

                                Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum

                                Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

                                P Offline
                                P Offline
                                PIEBALDconsult
                                wrote on last edited by
                                #24

                                Luc Pattyn wrote:

                                You can't escape nested try constructs

                                Sure I can, I'll write a method. And I did say that some times they're necessary. However, taking the least scope route, if you want to protect against Exceptions in a finally (and you shouldn't need too), then put the try/catch there.

                                1 Reply Last reply
                                0
                                • P PIEBALDconsult

                                  The outer try/catch in this example is pointless, remove it. If the catch in the outer try/catch actually does something (like log the Exception), then the inner try/finally should be removed and the finally moved out to make the try/catch into a try/catch/finally. Nested try/catches (while sometimes necessary) are a code smell and should be investigated thoroughly. (Or Thoreau[^]ly -- simplify simplify.)

                                  J Offline
                                  J Offline
                                  Jan Holst Jensen2
                                  wrote on last edited by
                                  #25

                                  Pointless with regards to how the code executes, but not pointless if you are debugging. The outer catch block gives you a place to put a breakpoint so you can see when exceptions occur. I expect that is the reason for it. But the outer try-catch block can be safely removed for production code.

                                  P 1 Reply Last reply
                                  0
                                  • J J4amieC

                                    ahhh, no no no. If your UI code is mixed with your database access code; you're doing it wrong If you show Exception messages unsanitized to your users; you're doing it wrong

                                    R Offline
                                    R Offline
                                    Rick van Woudenberg
                                    wrote on last edited by
                                    #26

                                    I totally agree with you, and I would never show an exception to a user. Hence the

                                    // or show something else..

                                    , but I still think that you should at least say something when anything important messes up, like .. euhh .. a database connection that fails ? I don't think it's wise to redirect general user messages that could be caused by an exception to the windows logs. Not very user friendly.

                                    1 Reply Last reply
                                    0
                                    • J J4amieC

                                      ahhh, no no no. If your UI code is mixed with your database access code; you're doing it wrong If you show Exception messages unsanitized to your users; you're doing it wrong

                                      G Offline
                                      G Offline
                                      Gary Wheeler
                                      wrote on last edited by
                                      #27

                                      J4amieC wrote:

                                      If your UI code is mixed with your database access code; you're doing it wrong
                                       
                                      If you show Exception messages unsanitized to your users; you're doing it wrong

                                      Ahhh, no. It depends upon the scope of the problem you're trying to solve. If this is a 1,000 line utility app that you're the only user for, this might be perfectly appropriate. If it's a 200,000 line client for a LOB app, then you might have issues.

                                      Software Zen: delete this;

                                      1 Reply Last reply
                                      0
                                      • J Jan Holst Jensen2

                                        Pointless with regards to how the code executes, but not pointless if you are debugging. The outer catch block gives you a place to put a breakpoint so you can see when exceptions occur. I expect that is the reason for it. But the outer try-catch block can be safely removed for production code.

                                        P Offline
                                        P Offline
                                        PIEBALDconsult
                                        wrote on last edited by
                                        #28

                                        Then put a catch on the try/finally.

                                        J 1 Reply Last reply
                                        0
                                        • P PIEBALDconsult

                                          Then put a catch on the try/finally.

                                          J Offline
                                          J Offline
                                          Jan Holst Jensen2
                                          wrote on last edited by
                                          #29

                                          Except if the exception occurs during execution of the finally-block...

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups