• (cs)

    <FONT size=2><FONT face=Georgia>Wow....Those are two really good ones!<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p></FONT></FONT>

    <FONT size=2><FONT face=Georgia>The regEx one is weird because at first it looks like the guy knows how to use them...and then he goes and iterates through the string...[:|]<o:p></o:p></FONT></FONT>

    <FONT size=2><FONT face=Georgia>The second one is....different, it does work but it'll consume a lot of time working through all those thrown exceptions....looks like he just finished his programming 101 class on using try/catch blocks and wanted to impliment them as soon as possible.<o:p></o:p></FONT></FONT>

     <o:p></o:p>

  • Rob (unregistered)

    I particularly like the last set of try/catch blocks:

    try{passwordTextBox.ConfigValue ="******";}
      catch{passwordTextBox.ConfigValue ="******";}

    In other words, if it doesn't work the first time, try it again in the catch block.  He apparently hadn't heard of the famous "tryharder" keyword.  [;)]

    Also love the "IsDirty = false;" line at the end when everything goes kerbloey.  I feel dirty already.  Must... wash... eyeballs...

  • Top Cod3r (unregistered)

    Maybe in the first example, he did that for performance reasons.  Regular expressions are notoriously slow and also lack thread safetly.

  • Fregas (unregistered)

    In the words of Southpark:

    [8][8] Dumb dumb dumb!  Dumb dumb dumb... [8][8]

  • diaphanein (unregistered) in reply to Top Cod3r

    Anonymous:
    Maybe in the first example, he did that for performance reasons.  Regular expressions are notoriously slow and also lack thread safetly.

    Then why use them at all??  Are strings immutable in java?  In .Net at least, you can guarantee that the string isn't going to change from underneath of you, so that wouldn't have been the issue.

    If that was really the case, and he's only checking for a-z, why not use something like the following?

    foreach( char c in str )
    {
       if ( c < 'a' || c > 'z' )
          return false;
    }
    return true;

     

    As for the second case, *shudder*.  I'll leave it at that.

  • James (unregistered) in reply to Top Cod3r

    Oh yes.. especially that [a-z] pattern... notoriously complex, painfully slow!!!

    It would have been better if he created a class representing a letter, with a method to test if an  arg passed in the method is equal to the letter, then created an instance of each class for each letter of the alphabet, loop over the string, and then for each char, loop over the letter objects, comparing each and every single one. if non match, raise an exception, and in the catch block....

    RECURSE!!!!!!

  • pbounaix (unregistered) in reply to James

    i have to admit, on the very first professional project i worked on, i did something simialar to the second example. :(

    it had to work, and that was a quick n' dirty solution. I looked at the code 3 months later and shuddered. the try/catches went from 17 to 1 !

  • A. Nonymous (unregistered) in reply to diaphanein

    ... Doesn't Java have the equivalent of isalpha(c) and islower(c)?

  • (cs) in reply to Top Cod3r

    Anonymous:
    Maybe in the first example, he did that for performance reasons.  Regular expressions are notoriously slow and also lack thread safetly.

    This is another of TopCoot3rs misinformation posts.  Maybe one day we will know if these are jokes or not.

  • (cs)

    All that needs to change is

    "[a-z]" --> "[a-z]*"

    With one more letter, the for loop can be removed.  The PatternSyntaxException is a "can't happen" situation, since we know the regexp is correct, it would indicate a bug in the regexp classes, so it does not much matter what happens in the catch block.

  • (cs) in reply to dubwai
    dubwai:
    This is another of TopCoot3rs misinformation posts.  Maybe one day we will know if these are jokes or not.

    They are.  I'll give you another example:

    The real WTF here is how difficult Java makes it to do something as simple as "on error resume next!"  Visual Basic is a much easier language, and I can't understand why anybody would choose to use Java if they don't have to.

    See how easy that was?  I didn't mean a single word of that.  VB is for stupid-heads.

  • (cs) in reply to A. Nonymous

    Anonymous:
    ... Doesn't Java have the equivalent of isalpha(c) and islower(c)?

    the java.lang.Character class has static methods isLetter(char ch) and isLowerCase(char ch)

  • (cs) in reply to loneprogrammer

    Is it just me, or is try/catch becoming ubiquitous?  Is this really supposed to be that common in C#?  I've been running into it increasingly in code examples and whatnot, and I ask myself "whatever happened to checking for errors BEFORE doing things"?  I can only imagine how much it slows your code down... and it also doesn't teach you how to keep your code from barfing in the first place.

    me <- C# newbie, longtime user of C++

  • (cs) in reply to loneprogrammer
    loneprogrammer:
    dubwai:
    This is another of TopCoot3rs misinformation posts.  Maybe one day we will know if these are jokes or not.

    They are.  I'll give you another example:

    The real WTF here is how difficult Java makes it to do something as simple as "on error resume next!"  Visual Basic is a much easier language, and I can't understand why anybody would choose to use Java if they don't have to.


    See how easy that was?  I didn't mean a single word of that.  VB is for stupid-heads.

    Are you saying that you are Top Cod3r?

  • (cs) in reply to Charles Nadolski

    Charles Nadolski:
    Is it just me, or is try/catch becoming ubiquitous?  Is this really supposed to be that common in C#?  I've been running into it increasingly in code examples and whatnot, and I ask myself "whatever happened to checking for errors BEFORE doing things"?  I can only imagine how much it slows your code down... and it also doesn't teach you how to keep your code from barfing in the first place.

    me <- C# newbie, longtime user of C++

    You don't use exceptions in C++?  I think you are missing the point of using exceptions.  Yes they are relatively expensive but if the condition is truly exceptional, they are generally superior to checking a return code or 'checking for errors'.

    It's impossible to check for every possible error condition before executing some code.  Are you going to verify the avialable memory before executing any line of code?

  • G McDorman (unregistered) in reply to loneprogrammer
    loneprogrammer:
    All that needs to change is

    "[a-z]" --> "[a-z]*"
    Actually, no. '*' means zero or more, so "[a-z]*" will match anything, even a string of non-letters.

    What will work is:
     "^[a-z][a-z]*$"
    or
     "^[a-z]+$"
    (Not all RE implentations support the '+' modifier, although according the Sun documentation the 1.5 JRE does; I don't know about earlier JREs. All implementations support the '^', '*' and '$' modifiers.)
  • Jonathan Pryor (unregistered) in reply to loneprogrammer

    All that needs to change is
    "[a-z]" --> "[a-z]*"

    Alas, "[a-z]*" will always match, including strings consisting only of numbers (since "1234" will have 0 matches, and * means 0 or more).

    To get closer to the original method, you would need to anchor the match to ^ (beginning of string) and $ (end of string), or "^[a-z]*$".  This would properly reject "1234" and "ab56" while accepting "abcd".

     - Jon

  • (cs) in reply to G McDorman

    Anonymous:

    (Not all RE implentations support the '+' modifier, although according the Sun documentation the 1.5 JRE does; I don't know about earlier JREs. All implementations support the '^', '*' and '$' modifiers.)

    All JREs that support the regex package support +

  • (cs) in reply to G McDorman

    Anonymous:

     "^[a-z]+$"
    (Not all RE implentations support the '+' modifier, although according the Sun documentation the 1.5 JRE does; I don't know about earlier JREs. All implementations support the '^', '*' and '$' modifiers.)

    All java implementations support the '+' modifier.  Furthermore, since it's in the java.util.regex javadoc, it's part of the platform spec, and any VM that doesn't is noncompliant.  This has been the case since Java 1.4 (the version when regex support was first added to the platform).

    That being said, there are several non-official regex libraries for java, and I have no idea what they do or do not support.

  • (cs) in reply to dubwai
    dubwai:
    It's impossible to check for every possible error condition before executing some code.  Are you going to verify the avialable memory before executing any line of code?


    Actually, yes.  It's very good practice to check if a handle/pointer is not NULL before even calling its methods.  If you always assign NULL whenever you delete a pointer or initialize it, you have an easy way of checking if it's valid.  You DO check the index of an array before accessing an array don't you?  I can honestly say that not ONCE have I ever called try/catch in my C++ code.  I don't ever call throw either (I use AfxMessageBox instead).
  • (cs) in reply to Charles Nadolski

    Charles Nadolski:

    Actually, yes.  It's very good practice to check if a handle/pointer is not NULL before even calling its methods.  If you always assign NULL whenever you delete a pointer or initialize it, you have an easy way of checking if it's valid.  You DO check the index of an array before accessing an array don't you?  I can honestly say that not ONCE have I ever called try/catch in my C++ code.  I don't ever call throw either (I use AfxMessageBox instead).

    What does null have pointers have to with available memory and since when are null pointers the only possible error condition?  You check the amount of memory available before every line of code you excute?  I really doubt that.

    Also, are you saying that you throw a dialog up on the screen on every error?  That's going to work great in my B2B translation software.  That is a terrible practice.

    I once worked on a project where I had to interface with another team's system using their code.  They had code that threw up a dialog on an error condition.  The problem was that my process was not running as a GUI it was a server based process.  So this error message dialog call would block and hang the whole process.  The other team had to assign a developer to rewrite the code to not do this at great expense.

  • (cs) in reply to dubwai
    dubwai:
    Are you saying that you are Top Cod3r?

    No.  My jokes are funny.

  • Brian (unregistered) in reply to Charles Nadolski

    Tomorrow on the TDWTF:

    <FONT face="Courier New">void* p = malloc(1);
    if (p == NULL) {
      AfxMessageBox("Out of memory");
    }
    else {
       free(p);
       p = NULL;</FONT><FONT face="Courier New">
       DoSomethingA();
    }
    <FONT face="Courier New">
    p = malloc(1);
    if (p == NULL) {
      AfxMessageBox("Out of memory");
    }
    else {
       free(p);
       p = NULL;<FONT face="Courier New">
       DoSomethingB();
    }
    </FONT>
    // ... and so on</FONT>

    </FONT>
  • (cs) in reply to loneprogrammer

    loneprogrammer:
    dubwai:
    Are you saying that you are Top Cod3r?

    No.  My jokes are funny.

    OK.  Glad we cleared that up.

  • (cs) in reply to Charles Nadolski

    <FONT face=Tahoma><FONT size=1>

    Charles Nadolski:

    I can honestly say that not ONCE have I ever called try/catch in my C++ code.  I don't ever call throw either (I use AfxMessageBox instead).
    <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p></FONT></FONT>

    <FONT face=Tahoma><FONT size=1>Really? So you are saying that everyone else that uses try/catch blocks don't know how to program properly and should not be using try/catch blocks?<o:p></o:p></FONT></FONT>

    <FONT face=Tahoma><FONT size=1>I agree that too many try/catch blocks are used by some programmers, but to not use any is wrong IMHO. As <!--StartFragment --> dubwai said they are to be used  when "the condition is truly exceptional". Exceptions should not be used to check if a variable is null, or if an array index is going to be out of range, but they should be used to "error gracefully" (as my friend used to say) when an unforeseen error occurs in your code since it's IMPOSSIBLE to know every error that may occur during a programs execution.<o:p></o:p></FONT></FONT>

    <FONT face=Tahoma><FONT size=1> <o:p></o:p></FONT></FONT>

  • (cs) in reply to G McDorman

    Anonymous:
    loneprogrammer:
    All that needs to change is

    "[a-z]" --> "[a-z]*"
    Actually, no. '*' means zero or more, so "[a-z]*" will match anything, even a string of non-letters.

    What will work is:
     "^[a-z][a-z]*$"
    or
     "^[a-z]+$"

    Yet again there seem to be as many WTF comments as there are in the original post.  loneprogrammer was correct.  I don't know if G McDorman and Jonathan Pryor are just trolling, but they seem serious enough

    The method "match" attempts to match the entire input sequence against the pattern (as opposed to the method "find", which only attempts to find a match within the input sequence).  so calling match with [a-z]* will match 0 or more lower case letters.  It will not match anything else.  Don't believe me?  Try it yourself:

    public class WTFRegex {
        public WTFRegex() {
            String[] vals = {"one", "TWO", "thr33", "wunderbar", "", "12345"};
            for(int i=0; i<VALS.LENGTH; i++){<BR>          System.out.println(vals[i] + " = " + quote_string_checker2(vals[i]));  
            }

        }
        public boolean quote_string_checker2 (String stringtoscan) { 
               Pattern p = Pattern.compile("[a-z]*");        
               Matcher m=p.matcher(stringtoscan);
               return m.matches();       
          }
       
        public static void main(String[] args){
           new WTFRegex();  
        }
    }

    Granted, your regex will work, and the ^ $ symbols don't hurt it, but they are unnecessary when using the method match.  Also the original method DID return true for an empty string, so your answer is slightly different

    WTF

    evanfets

  • Anonymous Coward (unregistered)

    To the folks who think that exceptions must be used:

    http://www.joelonsoftware.com/items/2003/10/13.html


  • rpresser (unregistered) in reply to Jonathan Pryor

    Much simpler way:

    public boolean quote_string_checker (<font style="background-color: rgb(211, 211, 211);">String</font> stringtoscan) {
    boolean testval;
    Pattern p = Pattern.compile("[^a-z]");
    Matcher m = p.matcher(stringtoscan);
    testval = m.matches();
    return (testval == false);
    }

  • (cs) in reply to Anonymous Coward

    Anonymous:
    To the folks who think that exceptions must be used:

    http://www.joelonsoftware.com/items/2003/10/13.html

    His assertion that you must use 'OUT parameters' in Java to return multiple values makes me kind of leery of his advice.

    I basically disagree with everything on that page about exception.  Deal with everything right away he says.  That's great.  What if it makes no sense to do that?  Like if you get an OOM exception in a library that you are writing.  What are you going to do, throw up a dialog?  Exit?

  • Jim (unregistered) in reply to Charles Nadolski
    I don't ever call throw either (I use AfxMessageBox instead).


    Please let this be a troll!!!

    As a programmer who uses a lot of MFC, this makes me want to just go lay down on the train tracks!  No wonder we get no respect!!!!!!

    That sentance alone is as big a WTF as has ever been posted here. 

    Holy Jebus!!!! Forget server apps.  What kind of GUI just throws up random message boxes here and there for error handling?!!!?????

    I feel dirty and my eyes are still burning just from reading that.
  • (cs) in reply to Anonymous Coward
    Anonymous:
    To the folks who think that exceptions must be used:

    http://www.joelonsoftware.com/items/2003/10/13.html




    Thanks, I was about to go on a rant, but that link explains exactly why I avoid try/catch like the plague.

    And to the reasoning "that you can't catch all exceptions", well good!  I don't expect to.  Because when the code barfs, it forces me to re-think how I implemented the code, and avoid precicely that exception in the future through good checks and design.  Moreover, the call stack will point me where the error happened and what the run-time error was, and a debugger will further help to narrow the offender down.
  • (cs) in reply to Jim
    Anonymous:
    I don't ever call throw either (I use AfxMessageBox instead).


    Please let this be a troll!!!

    As a programmer who uses a lot of MFC, this makes me want to just go lay down on the train tracks!  No wonder we get no respect!!!!!!

    That sentance alone is as big a WTF as has ever been posted here. 

    Holy Jebus!!!! Forget server apps.  What kind of GUI just throws up random message boxes here and there for error handling?!!!?????

    I feel dirty and my eyes are still burning just from reading that.


    Dear Mr. Kneejerk:

    What's so bad about a message box?  I give the user a customized error message, and I handle the error however it needs to be handled (exit the function with an error code, or continue with a modified code sequence).  It's no different than writing an error message to the console back in the non-gui days.

    Think carefully about what throw does.  From MSDN:

    THROW interrupts program execution, passing control to the associated CATCH block in your program. If you have not provided the CATCH block, then control is passed to a Microsoft Foundation Class Library module that prints an error message and exits.

    It's basically an interrupt with a goto. Do you really want this to happen? Instead I'm using code logic that I have complete control over to do the same thing.

    So Mr. Kneejerk with the multiple exclamation points, you prefer that NO information is relayed back to the user?  Or it's just quietly written to a log file?  Or you'd rather see the program say "Error reading (some hex number)" and just quit?  What is your solution?  Oh wait, you'd rather just go OMFG BS HAX!!!oneoneone.
  • (cs)

    RegEx is nice, RegEx is cool, RegEx is OVERKILL for [a-z]*, so the biggest wtf for the first one is why he bothered with regex at all.

    And that last code is simply exceptional (come on, someone had to say it!)

  • (cs) in reply to A. Nonymous

    Yes:

    java.lang.Character.isLetter(char ch)
    java.lang.Character.isLowerCase(char ch)



  • (cs)

    If you are using exceptions to control flow, then Joel is dead-on, that is worse than goto's.

    I don't throw many new exceptions, I reserve them for situations where a crash is better than a silent and unknown failure. The tend to have one style of message; The way it is now, nothing is going to work, you must have a working A and twiddle B.

    eg. The widget file cannot be read from the disk, it must exist and must be accessible to the application's user.

    I mostly catch exceptions and make them go away, I only do this when I know what to do. When parsing strings for numbers, there is usualy a buisness process, thus a default, so I will catch the FormatException and return 0.

    I think the WTF in these examples is the useless use of exceptions, not exceptions themselves.

    I don't work in java, but I assume java.util.regex.PatternSyntaxException is going to be thrown by a regex pattern and not the string input it checks. If so, then it appears that the specific exception will never be thrown. The pattern is hard coded. The loopiness is just silliness.

    The second example is just bad code, written by someone who doesn't understand functions, let alone exception handling, not catching anything, so just one finally??? . I guess the person is trying to handle DBNull.Value and/or null.

    IsDirty will always be true, finally is for cleaning up resources allocated in the try, not for normal program control. The finally block will be called, but can you find the documentation that says when exactly.

    email.ConfigValue = GetSafeValue(row.Email,""); // Do whatever you need in the function so you don't barf.

     

  • (cs) in reply to Free

    Also if you have ever done any backend work in an olap facility, theres nothing guaranteed to piss off a server admin than to have a server beep every now and then.

    So they log in to check. 4000 AFXMessageBoxes.

    GG.

    Also exceptions have a bit of overhead with the stack walk etc. Use them for exceptional cases!

    And dont bother the user if you can fix it yourself!

    And dont show the message box in the bowels of your Widget load code! You'll end up working on a more complex system some day and block an entire app with a message box, deep in the bowels of your database interaction tier. Double points if your error message needs to be loaded through the blocked connection. ;)

  • (cs) in reply to Charles Nadolski
    Charles Nadolski:
    Think carefully about what throw does.  From MSDN:

    THROW interrupts program execution, passing control to the associated CATCH block in your program. If you have not provided the CATCH block, then control is passed to a Microsoft Foundation Class Library module that prints an error message and exits.

    It's basically an interrupt with a goto. Do you really want this to happen? Instead I'm using code logic that I have complete control over to do the same thing.

    You could also just catch the exception.  This is a straw man.  You are saying you either don't use exceptions or you don't catch them.  No, you use them and catch them where appropriate.  I've worked in languages that do not support exceptions and I know from experience that they are better than return codes.  My humble opinion is that you aren't really understanding how to use exceptions effectively.

    A while loop is a goto with an conditional.  Do you fear using that?  Any control structure basically boils down to a goto.

    The problem with using dialogs is that you are coupling your code to a gui.  I would suggest reading up on MVC and other literature about separating different layters in your system.

  • (cs)

    Thought I'd chime in with my thoughts on exceptions ... http://weblogs.asp.net/alex_papadimoulis/archive/2005/04/01/396734.aspx

  • (cs) in reply to dubwai
    dubwai:

    You could also just catch the exception.  This is a straw man.  You are saying you either don't use exceptions or you don't catch them.  No, you use them and catch them where appropriate.  I've worked in languages that do not support exceptions and I know from experience that they are better than return codes.  My humble opinion is that you aren't really understanding how to use exceptions effectively.


    I stick to my original argument that you apply good design and good debugging so that exceptions just don't occurr.  If you know your program is a memory hog, check that there's enough memory for your program to use before it throws an exception.  If you're writing to a com port, check that you can use it before you get an exception.

    However, this doesn't mean there aren't legitimate uses for try catch, but that they should be extremely rare.  For situations that are nigh impossible to predict.  And if the try/catch is in somebody else's code, there's no point in trying to remove them if they just plain work.

    dubwai:

    A while loop is a goto with an conditional.  Do you fear using that?  Any control structure basically boils down to a goto.


    I'm well aware that a while loop becomes goto + branch in assembly (I coded a 2-D game all in ASM, so I wrote plenty of those).  However, would you write a goto and if() in C++ to do a while loop?  It's preference.  I'd rather check a condition with an if statement than wait for a interrupt (say for a divide by zero error) to halt my program.  I think that's reasonable enough.  In my haste I didn't make myself clear enough.

    dubwai:

    The problem with using dialogs is that you are coupling your code to a gui.  I would suggest reading up on MVC and other literature about separating different layters in your system.



    In this context, the coupling the gui isn't a big worry, since the whole damn program I was writing is in MFC and will never be ported to another language or operating system.  In theory I could have created a dialog class for handling certain error events, but AfxMessageBox is all I needed in terms of functionality.  On a slow day at the office I even got the program to run flawlessly in Wine.

    Maybe we're also approaching this issues with different purposes of our code.  I code scientific analyses software, where most error cases can be predicted, and others nailed with the debugger.  I don't ever have to deal with hairy situations with internet protocols, and I also don't have to deal with SQL-esque databases.  Try/Catch is simply a tool that's never really needed.

    I hope this is a more coherent response since I'm not typing furiously at work.  I also probably also deserve some smacking around since I'm relatively new to programming in a business environment.
  • Thomas Magle Brodersen (unregistered)
     this.IsDirty indeed!
  • Z (unregistered) in reply to skicow
    skicow:

    <font face="Tahoma"><font size="1">I agree that too many try/catch blocks are used by some programmers, but to not use any is wrong IMHO. As <!--StartFragment --> dubwai said they are to be used  when "the condition is truly exceptional". Exceptions should not be used to check if a variable is null, or if an array index is going to be out of range, but they should be used to "error gracefully" (as my friend used to say) when an unforeseen error occurs in your code since it's IMPOSSIBLE to know every error that may occur during a programs execution.<o:p></o:p></font></font>

    <font face="Tahoma"><font size="1"> <o:p></o:p></font></font>



    It isn't impossible. It just requires a different way of thinking about programs (i.e., as mathematical objects in a precisely defined domain).
  • Simon (unregistered) in reply to Charles Nadolski
    Charles Nadolski:
    I hope this is a more coherent response since I'm not typing furiously at work.  I also probably also deserve some smacking around since I'm relatively new to programming in a business environment.

    Personallly, I think you're not too far from the truth.

    Exceptions should be just that - exceptional circumstances. They shouldn't, IMO, be used as a 'standard' method of control flow. On top of that, there are very few circumstances where they should even be caught. In most cases, really exceptional circumstances are unrecoverable.

    Java of course buggers this nice idealistic concept up, as it requires you to declare all possible exceptions that can be thrown in a message, and if you don't catch the myriad exceptions that might be thrown in some low-level libraary then the 90% oof the methods of your application/library/whaatever will declare 'throws Exception` or similar.

    Java sucks.

    Simon

  • Z (unregistered) in reply to Free
    Free:


    <>IsDirty will always be true, finally is for cleaning up resources allocated in the try, not for normal program control. The finally block will be called, but can you find the documentation that says when exactly.

     </userdefined>


    At Java Virtual Machine Specification, where
  • Boobidoo (unregistered) in reply to Simon

    Anonymous:
    Java of course buggers this nice idealistic concept up, as it requires you to declare all possible exceptions that can be thrown in a message, and if you don't catch the myriad exceptions that might be thrown in some low-level libraary then the 90% oof the methods of your application/library/whaatever will declare 'throws Exception` or similar. Java sucks. Simon

    WTF? Java has the concept of checked and unchecked exceptions. With checked exceptions you are forced to think about catching error conditions or declaring them to your caller. You do not need to do this for unchecked exceptions (e.g. out of memory).

    Java itself doesn't suck, but Java code written by people who declare 90% of their methods with throws exception sucks.

    [:|]

    Boobidoo

  • (cs)

    speechless

  • ammoQ (unregistered)

    Exceptions are not like gotos, they are more like a "return" or "exit".
    But since they allow you to exit many functions/methods up the stack (until the exception get catched), they are in some respect much more powerfull than a simple goto could ever be.
    There are wonderfull ways to abuse exceptions, oh yes...

  • (cs) in reply to ammoQ

    I only use try/catch blocks when my code generates an error I have trouble tracing, and since Micrsoft's ECMAscript engines generate useless error messages, I need to strategically place try/catches to locate teh bug. I can't say how much influence the scrpting engine has; it might be that Gecko lets you read more from the error object, because it provides better error messages in general.

    I never use try/catch for 'custom' error messages, because if I can think of a custom error message, I can prevent the entire error with one line of code. Custom error messages are not for you, they are for users, and if your code is right, the messages never contain an actual error, just information like 'Cannot save empty value' and suchlike. Warnings and information, not errors like 'setVariable is undefined line X char Y'. It's called idiot-proofing your application.

    Other than that, I consider try/catch to be a development tool only, and should be removed once you finalize the code, because in theory, production code should be good. On a more emotional note, using try/catch in production code is kind of like admitting defeat before even... trying... eheh. K. It's just icky.

  • (cs) in reply to dhromed
    dhromed:

    Other than that, I consider try/catch to be a development tool only, and should be removed once you finalize the code, because in theory, production code should be good.


    Some things can just as well happen to good production code:
    - a network connection breaks
    - database tablespace runs out of free space
    etc.
  • Buff (unregistered) in reply to ammoQ

    OK, I don't mind exceptions used for proper purposes, they allow me to let an object that knows what should be done make a decision, rather than just letting the program fall over

    eg. a class that reads a file in for you should throw an exception if it can't find it, so the calling code can sort it out. The class reading the file has no idea how important reading that file is.

    My question to those who don't believe in using try/catches how would I re-write the following code to not use one?

    // assume the parameter was passed in an http request for instance
    String timesToRunParam = request.getParameter("timesToRun");
    int timesToRun = 1;
    try{
        accountId = Integer.parseInt(accountParam);
    }catch(NumberFormatException e){
        // print out message to error logs that something/someone's passing invalid parameter
    }

    Should I be testing that the String only contains a number before parsing it? Because that seems more icky to me than using exceptions.

  • (cs) in reply to Buff
    Anonymous:

    Should I be testing that the String only contains a number before parsing it? Because that seems more icky to me than using exceptions.


    Yes, the proper way would be to check the string beforehand.

      The easy way would be to ask yourself the question "Will the accountParam always be greater than zero"?  At least in C++, atoi(strSomeCString) will return zero if the string is not a number.  Check if accountID is zero.  This should handle a large number of cases.

      Otherwise, write a function that checks if it's a number, like bool StringIsNumber().  Not only is it a good learning experience, a function like that can  be used in a lot of places.  Also this function can be written to be very fast too, much much faster than parseInt I imagine.

    But  from  what I'm reading on this forum about  Java (I'm not a Java guy at all!), it seems the language encourages you to use try/catch in every conceivable situation...

     Back in the day when I was in my first programming class for C++ (cerca 1997, but I was coding on my own before then), the end-all and be-all to fixing errors was to have good return codes from functions.  The most basic ones returned true or false, or -1.  But the best system would be to define an enumeration that contained a list of error codes representing the kinds of custom errors your program would generate.  Instead of "catching" them using catch, you would send the return into an if statement or a switch like so:

    CString strFather;
    if(!mapStringToString.lookup("Father", strFather)
    {   //whoops, father doesn't exist yet!
        strFather = "Homer"
        mapStringToString.SetAt("Father", strFather);   //Assign a default
    }

    //Do stuff with strFather

    Of course, if you know in your head that "Father" has been 100% guaranteed to be created in the map, then you don't even need the if statement anymore.  Of course, I haven't delved into the brave new world of <leetspeek><1337speak> t3h int4rw3bs </leetspeek></1337speak> in terms of programming, so I may have to throw my idealism out the window :-D

Leave a comment on “Try. Catch. Throw Up.”

Log In or post as a guest

Replying to comment #:

« Return to Article