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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. using usage (IDisposable)

using usage (IDisposable)

Scheduled Pinned Locked Moved C#
question
15 Posts 6 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.
  • T TMattC

    Hi! I wonder if this code is a correct way of using the IDisposable using keyword. Can I put the try-catch block inside it like this, and is it fine to insert a return inside the usage block? (the code is part of a method)

    using(StreamReader reader = File.OpenText(fileName))
    {
    int lineIndex=0;
    string line;
    while((line=reader.ReadLine()) != null)
    {
    string[] fields = line.Split(';');
    try
    {
    prodLst.Add(new Produkt(Int64.Parse(fields[0]), (ProdKategoriEnum)Int32.Parse(fields[1]), fields[2], Int32.Parse(fields[3]), Int32.Parse(fields[4])));
    prodFileIndexDic.Add(Int64.Parse(fields[0]), lineIndex);
    lineIndex++;
    }
    catch(FormatException e)
    {
    return false;
    }
    }
    return true;
    }

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #4

    Not as an answer to your question, phil.o and OriginalGriff already covered that - but since you're apparently interested to learn about good practice: When simply returning false in case of an exception, you'll never know why exactly your code failed. You should either log the exception message (and possibly its stacktrace) to a logfile or reconsider if it's not even better to just let your exception "bubble up" - meaning, your method would simply be a void method: Continuation of program execution means all went well, otherwise the exception will also abort the execution of the calling code scope. This is in most cases the best approach and saves you from checking boolean success-return values "everywhere". Only catch an exception if you're going to do something with it: Logging and rethrowing it (potentially wrapped as an InnerException into a custom exception) or actually doing something to remedy the error so that the program can continue normally.

    Recursion: see Recursion.

    1 Reply Last reply
    0
    • T TMattC

      Hi! I wonder if this code is a correct way of using the IDisposable using keyword. Can I put the try-catch block inside it like this, and is it fine to insert a return inside the usage block? (the code is part of a method)

      using(StreamReader reader = File.OpenText(fileName))
      {
      int lineIndex=0;
      string line;
      while((line=reader.ReadLine()) != null)
      {
      string[] fields = line.Split(';');
      try
      {
      prodLst.Add(new Produkt(Int64.Parse(fields[0]), (ProdKategoriEnum)Int32.Parse(fields[1]), fields[2], Int32.Parse(fields[3]), Int32.Parse(fields[4])));
      prodFileIndexDic.Add(Int64.Parse(fields[0]), lineIndex);
      lineIndex++;
      }
      catch(FormatException e)
      {
      return false;
      }
      }
      return true;
      }

      J Offline
      J Offline
      jschell
      wrote on last edited by
      #5

      As an implementation note one should keep in mind that dispose (which happens with using) doesn't insure that exceptions cannot be thrown. Which is fine if you don't mind if an exception occurs on that last closing brace but if you are trying to create a fail safe method then it is inappropriate. One should also consider what the impact is to the business functionality. So for example in the given sample code if one successfully read the file but then the close fails (in the dispose) then does the application (business functionality) really care?

      1 Reply Last reply
      0
      • T TMattC

        Hi! I wonder if this code is a correct way of using the IDisposable using keyword. Can I put the try-catch block inside it like this, and is it fine to insert a return inside the usage block? (the code is part of a method)

        using(StreamReader reader = File.OpenText(fileName))
        {
        int lineIndex=0;
        string line;
        while((line=reader.ReadLine()) != null)
        {
        string[] fields = line.Split(';');
        try
        {
        prodLst.Add(new Produkt(Int64.Parse(fields[0]), (ProdKategoriEnum)Int32.Parse(fields[1]), fields[2], Int32.Parse(fields[3]), Int32.Parse(fields[4])));
        prodFileIndexDic.Add(Int64.Parse(fields[0]), lineIndex);
        lineIndex++;
        }
        catch(FormatException e)
        {
        return false;
        }
        }
        return true;
        }

        T Offline
        T Offline
        TMattC
        wrote on last edited by
        #6

        Ok guys, thanks for your help.

        1 Reply Last reply
        0
        • T TMattC

          Hi! I wonder if this code is a correct way of using the IDisposable using keyword. Can I put the try-catch block inside it like this, and is it fine to insert a return inside the usage block? (the code is part of a method)

          using(StreamReader reader = File.OpenText(fileName))
          {
          int lineIndex=0;
          string line;
          while((line=reader.ReadLine()) != null)
          {
          string[] fields = line.Split(';');
          try
          {
          prodLst.Add(new Produkt(Int64.Parse(fields[0]), (ProdKategoriEnum)Int32.Parse(fields[1]), fields[2], Int32.Parse(fields[3]), Int32.Parse(fields[4])));
          prodFileIndexDic.Add(Int64.Parse(fields[0]), lineIndex);
          lineIndex++;
          }
          catch(FormatException e)
          {
          return false;
          }
          }
          return true;
          }

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #7

          Why are you only catching "FormatException"? You prefer to crash otherwise? In this context, it only makes sense to catch the general "Exception" ... One can always use e.GetType().ToString() or "if (e is FormatException)..." to log any exception specifics if it came down to that and you did not want to use multiple catch blocks.

          Richard DeemingR 1 Reply Last reply
          0
          • L Lost User

            Why are you only catching "FormatException"? You prefer to crash otherwise? In this context, it only makes sense to catch the general "Exception" ... One can always use e.GetType().ToString() or "if (e is FormatException)..." to log any exception specifics if it came down to that and you did not want to use multiple catch blocks.

            Richard DeemingR Offline
            Richard DeemingR Offline
            Richard Deeming
            wrote on last edited by
            #8

            You should never catch the general "Exception" type, except in the entry point to your application where you simply log the exception and exit. In the OP's code, the try..catch block isn't needed, since there are TryParse methods which won't throw an exception if the input is invalid.


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

            L 1 Reply Last reply
            0
            • T TMattC

              Hi! I wonder if this code is a correct way of using the IDisposable using keyword. Can I put the try-catch block inside it like this, and is it fine to insert a return inside the usage block? (the code is part of a method)

              using(StreamReader reader = File.OpenText(fileName))
              {
              int lineIndex=0;
              string line;
              while((line=reader.ReadLine()) != null)
              {
              string[] fields = line.Split(';');
              try
              {
              prodLst.Add(new Produkt(Int64.Parse(fields[0]), (ProdKategoriEnum)Int32.Parse(fields[1]), fields[2], Int32.Parse(fields[3]), Int32.Parse(fields[4])));
              prodFileIndexDic.Add(Int64.Parse(fields[0]), lineIndex);
              lineIndex++;
              }
              catch(FormatException e)
              {
              return false;
              }
              }
              return true;
              }

              Richard DeemingR Offline
              Richard DeemingR Offline
              Richard Deeming
              wrote on last edited by
              #9

              As others have said, the code you've posted will work as expected. However, you can avoid the try..catch block by using the TryParse methods. You should also check the result of line.Split(';') to avoid an IndexOutOfRangeException, check that the second field is a valid Enum value, and check that the dictionary doesn't already contain the key:

              string[] fields = line.Split(';');
              if (fields.Length < 5) return false;

              // TODO: Give these variables proper names:
              long f0;
              int f1, f3, f4;

              if (!long.TryParse(fields[0], out f0)) return false;
              if (!int.TryParse(fields[1], out f1)) return false;
              if (!int.TryParse(fields[3], out f3)) return false;
              if (!int.TryParse(fields[4], out f4)) return false;

              // If the dictionary already contains the key, the Add method throws an ArgumentException:
              if (prodFileIndexDic.ContainsKey(f0)) return false;

              // Any integer can be cast to any enum without an exception;
              // you probably wany to check that it's valid first:
              if (!Enum.IsDefined(typeof(ProdKategoriEnum), f1)) return false;

              prodList.Add(new Produkt(f0, (ProdKategoriEnum)f1, fields[2], f3, f4));
              prodFileIndexDic.Add(f0, lineIndex);
              lineIndex++;


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

              1 Reply Last reply
              0
              • Richard DeemingR Richard Deeming

                You should never catch the general "Exception" type, except in the entry point to your application where you simply log the exception and exit. In the OP's code, the try..catch block isn't needed, since there are TryParse methods which won't throw an exception if the input is invalid.


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #10

                You have no idea what he has "higher up". I said: "in this context". You also can't seem to tell the difference between "Parse" and "TryParse". You should "never" shoot your mouth off before thinking. Take you down vote and ....

                Richard DeemingR 1 Reply Last reply
                0
                • L Lost User

                  You have no idea what he has "higher up". I said: "in this context". You also can't seem to tell the difference between "Parse" and "TryParse". You should "never" shoot your mouth off before thinking. Take you down vote and ....

                  Richard DeemingR Offline
                  Richard DeemingR Offline
                  Richard Deeming
                  wrote on last edited by
                  #11

                  Gerry Schmitz wrote:

                  You have no idea what he has "higher up".

                  Doesn't matter - swallowing every exception "just-in-case" is still a bad idea.

                  Gerry Schmitz wrote:

                  You also can't seem to tell the difference between "Parse" and "TryParse".

                  What?! I suggest you try reading my comments again.

                  Gerry Schmitz wrote:

                  You should "never" shoot your mouth off before thinking.

                  Talking to yourself is the first sign of madness.


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                  L 1 Reply Last reply
                  0
                  • Richard DeemingR Richard Deeming

                    Gerry Schmitz wrote:

                    You have no idea what he has "higher up".

                    Doesn't matter - swallowing every exception "just-in-case" is still a bad idea.

                    Gerry Schmitz wrote:

                    You also can't seem to tell the difference between "Parse" and "TryParse".

                    What?! I suggest you try reading my comments again.

                    Gerry Schmitz wrote:

                    You should "never" shoot your mouth off before thinking.

                    Talking to yourself is the first sign of madness.


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #12

                    He was using "Parse" ... I never said "every" or "just-in-case" either ...

                    Richard DeemingR 1 Reply Last reply
                    0
                    • L Lost User

                      He was using "Parse" ... I never said "every" or "just-in-case" either ...

                      Richard DeemingR Offline
                      Richard DeemingR Offline
                      Richard Deeming
                      wrote on last edited by
                      #13

                      Which will throw an exception when the input cannot be parsed. Which is why I suggested using TryParse, which doesn't throw an exception. Which would then mean that he wouldn't need a try..catch block to catch the exception from the Parse method.


                      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                      L 1 Reply Last reply
                      0
                      • Richard DeemingR Richard Deeming

                        Which will throw an exception when the input cannot be parsed. Which is why I suggested using TryParse, which doesn't throw an exception. Which would then mean that he wouldn't need a try..catch block to catch the exception from the Parse method.


                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #14

                        I was talking about his post ... not some side post of yours. Give it a rest; I know what TryParse is for.

                        L 1 Reply Last reply
                        0
                        • L Lost User

                          I was talking about his post ... not some side post of yours. Give it a rest; I know what TryParse is for.

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #15

                          Point Nazis.

                          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