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. Other Discussions
  3. The Weird and The Wonderful
  4. try-catch Oo [modified]

try-catch Oo [modified]

Scheduled Pinned Locked Moved The Weird and The Wonderful
helpsalesquestiondiscussion
14 Posts 10 Posters 43 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.
  • R Robert Royall

    Oddly enough, I ran into a place where I have to use this in a WPF app I'm working up for my boss. In code, if you try to load an Image control, you can't just give it a filename, you have to give it an ImageSource object. The most obvious of these is BitmapSource, which inherits from ImageSource. BitmapSource won't take a filename either - it requires a Uri object, which is (as its name implies) a URI to a file somewhere. BitmapSource has one strange little caveat. Its properties are immutable. Nothing you change will stick unless you explicitly call the BeginInit method on it. Once you're done, call EndInit and all your changes are persisted. Herein lies the problem. My application calls BeginInit on a BitmapSource and runs through a switch that looks at the application state to decide which image to load. If the switch detects an invalid state, it sets the Uri to null (so that no images load). Then, at the end of the switch, I call EndInit and my BitmapSource should have loaded either an image file or nothing at all. Here's the kicker. BitmapSource throws an exception if you call EndInit without setting a Uri. (Well, a Uri or a StreamSource, but I'm not dealing with streams in my app.) So in the case where the switch didn't load an image in its default case, my BitmapSource blows up. Unfortunately, whoever designed the interface that ImageSource implements (the one that contains BeginInit and EndInit) didn't seem to realize this fact, and neglected to include an AbortInit method. In other words, once you call BeginInit, you have to load an image somehow or catch the error that results from an empty URI. X| So yeah, my method now looks like this:

    imgLoader.BeginInit();
    switch(stateVar)
    {
    // case statements
    default:
    imgLoader.UriSource=null;
    break;
    }

    // Handle any errors thrown by imgLoader because of an empty UriSource
    try
    {
    imgLoader.EndInit();
    }
    catch { }

    Sad, isn't it?

    Please don't bother me... I'm hacking right now. Don't look at me like that - doesn't anybody remember what "hacking" really means? :sigh:

    C Offline
    C Offline
    Chris Meech
    wrote on last edited by
    #5

    I might be misunderstanding, but shouldn't you still have some code in the catch block to ensure that your stateVar variable is invalid. Otherwise you won't know about exceptions when the exception is meaningfull? :)

    Chris Meech I am Canadian. [heard in a local bar] Donate to help Conquer Cancer[^]

    R 1 Reply Last reply
    0
    • N Nemanja Trifunovic

      C'mon, that's just the C# way of saying On Error Resume Next


      Programming Blog utf8-cpp

      O Offline
      O Offline
      Oshtri Deka
      wrote on last edited by
      #6

      I wish it was that simple.

      1 Reply Last reply
      0
      • R Robert Royall

        Oddly enough, I ran into a place where I have to use this in a WPF app I'm working up for my boss. In code, if you try to load an Image control, you can't just give it a filename, you have to give it an ImageSource object. The most obvious of these is BitmapSource, which inherits from ImageSource. BitmapSource won't take a filename either - it requires a Uri object, which is (as its name implies) a URI to a file somewhere. BitmapSource has one strange little caveat. Its properties are immutable. Nothing you change will stick unless you explicitly call the BeginInit method on it. Once you're done, call EndInit and all your changes are persisted. Herein lies the problem. My application calls BeginInit on a BitmapSource and runs through a switch that looks at the application state to decide which image to load. If the switch detects an invalid state, it sets the Uri to null (so that no images load). Then, at the end of the switch, I call EndInit and my BitmapSource should have loaded either an image file or nothing at all. Here's the kicker. BitmapSource throws an exception if you call EndInit without setting a Uri. (Well, a Uri or a StreamSource, but I'm not dealing with streams in my app.) So in the case where the switch didn't load an image in its default case, my BitmapSource blows up. Unfortunately, whoever designed the interface that ImageSource implements (the one that contains BeginInit and EndInit) didn't seem to realize this fact, and neglected to include an AbortInit method. In other words, once you call BeginInit, you have to load an image somehow or catch the error that results from an empty URI. X| So yeah, my method now looks like this:

        imgLoader.BeginInit();
        switch(stateVar)
        {
        // case statements
        default:
        imgLoader.UriSource=null;
        break;
        }

        // Handle any errors thrown by imgLoader because of an empty UriSource
        try
        {
        imgLoader.EndInit();
        }
        catch { }

        Sad, isn't it?

        Please don't bother me... I'm hacking right now. Don't look at me like that - doesn't anybody remember what "hacking" really means? :sigh:

        O Offline
        O Offline
        Oshtri Deka
        wrote on last edited by
        #7

        Yes, but you had no choice, this guy put it in a block for filling part of dataSet. He was just lazy (or had no clue what he was doing).

        1 Reply Last reply
        0
        • C Chris Meech

          I might be misunderstanding, but shouldn't you still have some code in the catch block to ensure that your stateVar variable is invalid. Otherwise you won't know about exceptions when the exception is meaningfull? :)

          Chris Meech I am Canadian. [heard in a local bar] Donate to help Conquer Cancer[^]

          R Offline
          R Offline
          Robert Royall
          wrote on last edited by
          #8

          Not really; the only invalid stateVar that should get caught by the default case is 0 (i.e. don't display any images). There's a handler that should set the Image object to null, rather than its URI in this case, but there's still a couple of cases where the application changes to state 0 and runs the switch statement instead. (These cases shouldn't exist but I didn't write up a full state diagram because this application is a tech demo my boss wants to present to his peers and he doesn't want me to spend a lot of time on it. Go figure.)

          Please don't bother me... I'm hacking right now. Don't look at me like that - doesn't anybody remember what "hacking" really means? :sigh:

          1 Reply Last reply
          0
          • O Oshtri Deka

            I have found, on several places in our app, code similar to this: try { //some code here }catch{} :confused: Do I need to say I have found that during urgent debugging session (important customer had had complaints) Empty catch blocks, and most of them were in methods which deal with data. Let's just say that we use multi-threading and reflection, a lot, and I spent too much time on only localizing this. Why are people so reckless? I am far from being expert, but everyone who likes to think about oneself as a coder or developer should use common sense. :mad: Notice: Somehow (perhaps in a state of fury) I have forgotten to describe places where I had found above mentioned problem, and that has made this post is a bit misleading. Programmer who have written that code, used this "technique" only to sweep things under the rug! No returning values, filling dataSets, no validation, allowing bad user input (constraint violations)... in short error-exception domino which occurs only in specific situations. I am aware that empty try-catch block isn't excuse for witch hunt, but (at least) generally it isn't best practice. When I am not sure if something is preferable, I ask more experienced colleagues. -- modified at 6:31 Tuesday 20th November, 2007

            B Offline
            B Offline
            Brady Kelly
            wrote on last edited by
            #9

            It just occurred to me now, to replace the empty catch with an insulting error message. That will change management's view that proper exception handling is a waste of time.

            Cranial Apocalypse

            Calling all South African developers! Your participation in this local dev community will be mutually beneficial, to you and us.

            1 Reply Last reply
            0
            • O Oshtri Deka

              I have found, on several places in our app, code similar to this: try { //some code here }catch{} :confused: Do I need to say I have found that during urgent debugging session (important customer had had complaints) Empty catch blocks, and most of them were in methods which deal with data. Let's just say that we use multi-threading and reflection, a lot, and I spent too much time on only localizing this. Why are people so reckless? I am far from being expert, but everyone who likes to think about oneself as a coder or developer should use common sense. :mad: Notice: Somehow (perhaps in a state of fury) I have forgotten to describe places where I had found above mentioned problem, and that has made this post is a bit misleading. Programmer who have written that code, used this "technique" only to sweep things under the rug! No returning values, filling dataSets, no validation, allowing bad user input (constraint violations)... in short error-exception domino which occurs only in specific situations. I am aware that empty try-catch block isn't excuse for witch hunt, but (at least) generally it isn't best practice. When I am not sure if something is preferable, I ask more experienced colleagues. -- modified at 6:31 Tuesday 20th November, 2007

              C Offline
              C Offline
              Chris Losinger
              wrote on last edited by
              #10

              it happens. primarily because not everything thrown is worth worrying about. sometimes just knowing the operation failed is enough.

              int SafeParse(string bar)
              {
              int p = 0;
              try
              {
              p = int.Parse(bar);
              }
              catch () {}

              return p;
              }

              maybe i don't care to know if the string wasn't a number, because zero is a perfectly adequate default value and it's not worth bothering the user about.

              image processing toolkits | batch image processing

              S M 2 Replies Last reply
              0
              • C Chris Losinger

                it happens. primarily because not everything thrown is worth worrying about. sometimes just knowing the operation failed is enough.

                int SafeParse(string bar)
                {
                int p = 0;
                try
                {
                p = int.Parse(bar);
                }
                catch () {}

                return p;
                }

                maybe i don't care to know if the string wasn't a number, because zero is a perfectly adequate default value and it's not worth bothering the user about.

                image processing toolkits | batch image processing

                S Offline
                S Offline
                StM0n
                wrote on last edited by
                #11

                unfortunately, <> isn't implemented in all types...

                (yes|no|maybe)*

                1 Reply Last reply
                0
                • C Chris Losinger

                  it happens. primarily because not everything thrown is worth worrying about. sometimes just knowing the operation failed is enough.

                  int SafeParse(string bar)
                  {
                  int p = 0;
                  try
                  {
                  p = int.Parse(bar);
                  }
                  catch () {}

                  return p;
                  }

                  maybe i don't care to know if the string wasn't a number, because zero is a perfectly adequate default value and it's not worth bothering the user about.

                  image processing toolkits | batch image processing

                  M Offline
                  M Offline
                  Mycroft Holmes
                  wrote on last edited by
                  #12

                  Why not use IsNumeric to avoid the error Is ignoring the error less stressfull that testing bar? :~

                  Quote from Great Outdoors: its a confident traveller who farts in India

                  C 1 Reply Last reply
                  0
                  • M Mycroft Holmes

                    Why not use IsNumeric to avoid the error Is ignoring the error less stressfull that testing bar? :~

                    Quote from Great Outdoors: its a confident traveller who farts in India

                    C Offline
                    C Offline
                    Chris Losinger
                    wrote on last edited by
                    #13

                    that's an example; not the only time it happens.

                    image processing toolkits | batch image processing

                    1 Reply Last reply
                    0
                    • N Nemanja Trifunovic

                      C'mon, that's just the C# way of saying On Error Resume Next


                      Programming Blog utf8-cpp

                      W Offline
                      W Offline
                      Ware Work
                      wrote on last edited by
                      #14

                      Actually it's worse, more like On Error Goto ...

                      WarePhreak Programmers are tools to convert caffiene to code.

                      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