• diaphanein (unregistered) in reply to danixdefcon5

    [quote user="danixdefcon5Same I thought. Finally blocks always execute, the only way they wouldn't execute would be in situations where no code will get executed, like kill -9'ing the process, or on power down. Anyway, any critical transactions should be inside a transaction block themselves, so these two cases would cause an auto-rollback anyway!

    Note: finally blocks will run even if the exception thrown is an unchecked one (i.e. RuntimeException).[/quote]

    Yes, but it pays to be aware of the situations in which they will not execute.

    Just last week, I wasted half a day debugging a production issue where an app, despite checking all error codes, wrapping all pertinent calls in try/catch blocks was failing silently. No error, not log, no non-zero exit status. As it turns out, a 3rd party library was graciously calling exit_group for me. Only way I was even able to find that was by doing an strace.

  • Paula Bean (unregistered) in reply to Alex Papadimoulis
    Alex Papadimoulis:
    morry:
    where are you supposed to put the code? Magic fairy blocks?

    This answers it pretty well...

    Satanicpuppy:
    The secret is not to guarantee that your code will be completely executed, it is to guarantee that it will not be partially executed. Having a program fail completely is no problem at all...No harm, no foul, just run it again. Having it partially fail will screw up your whole week; that's why he mentioned database transactions.

    Using a Finally like they used it would be fine if all the Finally did was commit the transaction or something...Trusting it to break new ground is a recipe for the sort of subtle failure that makes you tear your hair out.

    ... but to expand on that, from a code perspective, if you're lucky enough to have an underlying transactional system, it's like this:

    try { StartTransaction(); DoStuff(); } catch { RollbackTransaction(); } finally { CommitIfNotRolledBack(); }

    The underlying transaction system will auto-rollback if it never gets committed or rolledback. However, the real problem occurrs when someone doesn't have an underlying transactional system.

    try { ProcessAllRecords(); } catch //(or a conditional finally) { UndoAllProcessing();
    }

    If ProcessRecords() is not designed to be re-entrant, then you're pretty much screwed if an error occurs and UndoAllProcessing() never is run.

    To make matters worse, these problems compound themselves, so the second time you run the program, the un-catchable exception occurs again and further corrupts the underlying data.

    Finally should be used for things like memory cleanup so you don't end up with leaks, etc. If the program never hits that kind of finally block, it's OK, since the whole thing has crashed and burned already, and memory leaks are the least of your worries.

    Aha!
    Thanks, I really appreciate this explanation.
    Twice the benefit from today's visit!

  • DL (unregistered) in reply to anon
    anon:
    actually, you could return to jump over the finally, code still executes, just not the finally.

    Sorry, that's incorrect. If you call "return" from within the "try" block, "finally" is still executed - that's the point!

  • Dave (unregistered) in reply to anon
    anon:
    zoips:
    anon:
    I almost never use finally, if you want to do stuff after a try-catch block then you don't really need the finally, these two blocks are almost always the same:

    try { result = a/b } catch (exception) { //handle divide by 0 } finally { return result }

    try { result = a/b } catch (exception) { //handle divide by 0 } return result

    also, any "mission critical" tasks would fare the same, and should have been recorded in a log system like a database uses instead of being 100% reliant on the code always executing

    finally is intended for (an attempt at) graceful cleanup when you plan to propagate the exception up the stack. At least that's always been my impression.

    I'll agree with you there. but I don't like exceptions to go outside of the function it happened in, I tend to prefer using if statements to validate input and take care of any problems that arise. if I have to interface with something that throws exceptions (for example most pre-built DB handlers only use that) I use try-catch as a replacement for if. if this code doesn't work, handle all the errors and cleanup gracefully and return a standard response of what happened instead of complaining to the routine that requested the function to run.

    Is that a subtle FILE_NOT_FOUND joke?

  • (cs)
    “Min,” I questioned, “why would put all these skills and technologies"

    Good idea to talk like her to really get the point across. Very effective. My big brother does that to pick up women at Chinese restaurants. With hands in the praying position he says, "Prease to be going out on date with me? I rike you."

  • Jason Bock (unregistered) in reply to anon

    Holy crap, DON'T catch the general exception type!

  • Dave (unregistered) in reply to Jason Bock
    Jason Bock:
    Holy crap, DON'T catch the general exception type!

    As long as you rethrow its not the end of the world.

  • blah (unregistered)

    TRWTF is this article has more sloppy typos than Min's resume's bad Engrish.

  • Morasique (unregistered) in reply to BentFranklin
    BentFranklin:
    Someone please educate me a bit: How does a database survive a power cycle in the middle of writing a transaction?

    Captcha: appellatio (A program that sucks?)

    Usually databases use journaling, so the change is logged in the journal before it actually happens. When the database starts, it checks the end of the journal to make sure it wasn't killed abnormally, and rolls back or commits whatever it needs to based on the journal to make the actual database consistent

  • (cs) in reply to Brandon
    Brandon:
    if(computer.IsOver || computer.IsAboutToBeOver) { //execute critical business code }

    I win.

    You forgot to add

    if(Virus == Very Yes)

    You won, but that's not a good prize.

  • (cs)

    I've only had one bad interview experience. The lead was called in to handle the technical portion of the interview, which was made up of a few questions.

    One of the questions was 'How would you detect if you had a circular reference in a linked list?' I responded that you'd have to use some type of a hash table and iterate over the list - at each element, you'd need to check the hash table to see if you'd ever seen that element before - if you had, there is a circular reference, if not, add it to the hash and continue.

    The interviewer kinda smirked at me and said something along the lines of 'Well that is not efficient - is there a more efficient way to do it' to which I responded 'Not that I can think of...'

    In a condescending way he suggested that there was a much better way to check, that was quicker, less memory intensive, etc etc, and gave me the hint 'What about the first item in the list??? - what can you do with it that would make this easier?' I should have seen that the solution he was driving at, even though I thought it was wrong. After a while he gave me his answer which was to just compare the first element to each additional element in the list, if you ever get back to it you have a circular reference, still smirking like he was the smartest guy that I'd ever meet.

    At this point, I suggested that his solution was flawed - what if the circular reference did not point back to the first element, it would fail to detect it, such as:

    A points to B which Points to C which points back to B. In this case you'll never get back to 'A'.

    He ended the interview at this point and I never heard from them. Not sure if this was the reason why they did not call back or if it was just due to other reasons... or my solution was shitty... I guess I don't really care, the job was downtown, which I try to avoid like the plague.

  • (cs) in reply to anon
    anon:
    actually, you could return to jump over the finally, code still executes, just not the finally.
    Not in all languages. In Java, finally always executes, even when already returning.
    try { return true; } finally { return false; }
    returns false, not true (nor FILE_NOT_FOUND).
  • Axel R. (unregistered) in reply to danixdefcon5
    danixdefcon5:
    The only blooper I might pass, however, might be something like "Microsoft Sybase" or "Sybase SQL Server", as they are practically the same thing. Except Sybase actually runs in non-MS platforms!

    I hope your employer is not reading this, as MS SQL Server and Sybase SQL Server parted completely in... 1998 with the introduction of SQL Server 7.0

  • (cs)

    I am good at interviews, I have gotten the last 5 interviews I went for. I can talk the talk, and have some good experience in a variety of positions. I used to really bad at interviews, didn't get a job offer after about 30 or 40 tries.

    The thing is, I was a much better programmer in those days. I cared a lot about learning new stuff, would go home and program for fun. Would learn new languages for fun, and write some interesting applications. Now I don't care about it that much, don't program much outside of work, don't work as hard. But because I am good at interviews, I can get the job. Brillant!

  • Jay (unregistered) in reply to JonC
    JonC:
    Surely TRWTF is giving someone who has 'Oracle T-SQL' and 'Microsoft Solaris' on their CV the benefit of the doubt.

    Personally I'd give someone the benefit of the doubt on "Microsoft Solaris". I'd chalk it up to clumsy wording. Sun has a version of Solaris that runs on Intel platforms. Someone who installed Solaris on their Wintel box might carelessly refer to it as "Microsoft Solaris". Wrong? Yes. A lie? Not necessarily.

    In general, I'm always cautious about ridiculing someone for making a dumb statement for fear that maybe it will turn out that their statement is correct and I only thought it was wrong because they know something that I don't. I don't want to laugh at someone and call him an idiot ... and then find out that he's right and I'm wrong. I prefer to ask for clarification before deciding someone's an idiot. A little humility can save you a lot of embarassment.

  • Camel Chase (unregistered) in reply to SQB

    Also a finally gets executed no matter what Exception hits.

    Consider:

    		try {
    			db.begin;
    			// do Stuff
    			Object o = null;
    			o.getClass(); // NullPointerException
    			
    			db.commit(); 
    			db.close(); // <--Problem
    			db = null;
    		} catch (NumberFormatException nfe) {
    			db.rollback();
    			db.close;
    			db = null;
    			// return error
    		} finally {
    			// free the db handle.
    			if (db != null) {
    				try {db.rollback(); db.close();} catch (Exception e) {}
    			}
    		}
    

    Your code is probably wrong (not cxhecking for null), but it doesn't chew up your db handles.

    kthxbye.

  • bcharr2 (unregistered) in reply to shepd
    shepd:
    Too many employers would take a fresh graduate that lists 15 languages you want them to know on their resume they "learned" in some school at god-knows-where over someone who has been in IT for a decade, but only has 10 of the 15 qualifications you want. And I'm just talking about offering them an interview. Once you offer the interview, it becomes obvious who is best for the job.

    Guess who is going to figure out how to get the job done faster and with fewer errors... And guess who is going to be far more useful to your company when hard times come.

    There is no hard and fast rule to the "Who is better, the college taught or self taught programmer?", because no 2 job candidates are exactly alike.

    I've seen individuals with degrees and without who could program. I've seen individuals with degrees and without who couldn't program.

    Oftentimes the best team can be a mix of those with and without degrees, assuming everyone involved can program.

    Which was the point of the article. The lady in question COULD NOT program, she simply knew how to use applications that had been developed in the languages that appeared on her resume.

    I once had a resume cross my desk that listed the following under programming languages: Word, Office, Excel. The gentlemen involved seemed like a nice guy, stated his love for computers over and over, and couldn't stress enough how fast of a learner he was. Did he get the job?

    No, he didn't even get to interview. If he loved programming that much, he would have taken the time to learn enough to be an asset to the company.

    This isn't a hero's quest, and I'm not your grandfatherly mentor who is going to peer deep down into your soul looking for all of your hidden potential that is just waiting to come out.

    In fantasy, heroes emerge at the moment of crisis and somehow seem to have all the skills they need. In the real world, the men and women who have committed themselves to years of preparation and training carry the day.

  • (cs) in reply to Ken B
    Ken B:
    Human Resources was a bit peeved that my group was so “picky” with our candidates ad rejected all of the qualified candidates (read: one) that they had sent over.
    You could have said "and I suppose you wanted me to hire *all* of the candidates you sent over?"

    You could give all of them numbered marathon jerseys, and refer to them by number instead of name. And when one screws up, you fire him on the spot. Last person standing gets the job.

  • Old fart (unregistered) in reply to unther

    If he was clairvoyant then you'd think he would have seen it coming...

  • Jay (unregistered) in reply to kswanton
    kswanton:
    At this point, I suggested that his solution was flawed - what if the circular reference did not point back to the first element, it would fail to detect it, such as:

    A points to B which Points to C which points back to B. In this case you'll never get back to 'A'.

    He ended the interview at this point and I never heard from them. Not sure if this was the reason why they did not call back or if it was just due to other reasons... or my solution was shitty... I guess I don't really care, the job was downtown, which I try to avoid like the plague.

    I've had occasions where an interviewer has asked me a flawed question like that, and I always struggle with what to do about it. If you concede the point, then you're "admitting" that you didn't know the right answer, and presumably you're going to lose points. But if you point out the interviewer's error, there's the likelihood that he's then going to resent you and not want to give you the job.

    Of course, one could argue that you wouldn't want to work for someone who refuses to admit his own mistakes and demands that everyone who works for him treat every stray remark he makes like a pronouncement from God. It all depends whether you're looking for the perfect job, or if you're currently unemployed and will take ANYTHING that pays the bills.

  • NE (unregistered)

    It claims succinctly with the example that the code always runs: http://msdn.microsoft.com/en-us/library/ke0zf0f5(VS.71).aspx

    Of course the documentation does suggest you run resource clean up in there, but who reads between the lines anyway?

  • (cs) in reply to kswanton
    kswanton:
    One of the questions was 'How would you detect if you had a circular reference in a linked list?' I responded that you'd have to use some type of a hash table and iterate over the list - at each element, you'd need to check the hash table to see if you'd ever seen that element before - if you had, there is a circular reference, if not, add it to the hash and continue.
    I said the same thing, except the question asked of me was something to the tune of "How would you find if you have a circular reference and where that reference begins." To that, I replied something similar to yours, and the interviewer asked me if I could think of anything else... to which i said "Not off the top of my head." The correct answer to the question you were asked is: Create 2 pointers, one that traverses the list one at a time, and one that traverses the list two at a time. If they are ever equal, you have a circular reference. If you encounter the end, you don't. However... that only works when you're not trying to find the beginning of the list... which my interviewer decided to add on to the question. (The actual question is from what Google made up for one of their interviews when they were hiring, btw)
  • (cs) in reply to bcharr2
    bcharr2:
    I've seen individuals with degrees and without who could program. I've seen individuals with degrees and without who couldn't program.
    That's what I'm getting at, I suppose. I've seen, around my area (EXTREME university influence), that >50% of employers list half-way decent paying jobs this way:

    Requirements:

    • Bachelor's degree or higher in Computer Science
    • Ability to commit to schedules

    Preferences:

    • Ability to program in [insert 5 - 10 current languages]
    • X years experience as an IT professional

    Then again, these places tend to be University upstarts that last for a couple of years and go bust (IMNSHO, due to a lack of perspective that you can only get from seasoned employees) so perhaps it's best they give me the warning up front.

    Every single place I've ever snagged an interview with has offered me a job. The thing is, even after having others in the industry review my resume several times, I get perhaps one interview out of two dozen applications. Usually due to the above requirements... sigh Luckily, I don't plan to leave my present job any time soon! Yay decent jobs! :-P Speaking of that, back to work...

  • GMo (unregistered) in reply to Ken B
    Ken B:
    Human Resources was a bit peeved that my group was so “picky” with our candidates ad rejected all of the qualified candidates (read: one) that they had sent over.
    You could have said "and I suppose you wanted me to hire *all* of the candidates you sent over?"

    Logic doesn't work on HR types.

  • blagger (unregistered) in reply to BentFranklin

    "Someone please educate me a bit: How does a database survive a power cycle in the middle of writing a transaction?"

    Any decent database has a transaction log. When the database comes back up it checks the log and rolls back any incomplete transactions.

    You're welcome.

  • (cs) in reply to BentFranklin
    BentFranklin:
    Someone please educate me a bit: How does a database survive a power cycle in the middle of writing a transaction?

    Captcha: appellatio (A program that sucks?)

    Transactions don't mean jack until they're committed. That's the whole point. If it fails in the middle, the database will just toss the info as a bad write. If it fails the commit, same thing. If the commit succeeds, then there is no problem.

    Transactional databases can't have bad or incomplete writes. That's just the way it works.

  • (cs) in reply to anon
    anon:
    I almost never use finally, if you want to do stuff after a try-catch block then you don't really need the finally, these two blocks are almost always the same:

    try { result = a/b } catch (exception) { //handle divide by 0 } finally { return result }

    try { result = a/b } catch (exception) { //handle divide by 0 } return result

    also, any "mission critical" tasks would fare the same, and should have been recorded in a log system like a database uses instead of being 100% reliant on the code always executing

    This will probably be said by several people before I finish typing this, but a "finally" block is always executed before the program continues -- even if you return or break from a loop from inside a "try" block.

    For example:

    public int connectAndGetStatus() {
        SomeConnection conn = new SomeConnection();
        conn.connectTo('example.com');
        try {
            return conn.getStatus();
        } finally {
            conn.close();
        }
    }
    

    In this case, conn.close() will be called whether conn.getStatus() succeeds or throws an exception. Since there is no catch clause, the exception will be propogated to the caller.

  • ok new as (unregistered)

    its drum n bass but...... ok was chatting with this girl 2nyt right, she was with her mum. her mom was yuck but damn she was hawt/ super sexy/ damn. shit fuck. JUNGLIST forever bitches. so hawt was her not het mom

  • (cs) in reply to Axel R.
    Axel R.:
    danixdefcon5:
    The only blooper I might pass, however, might be something like "Microsoft Sybase" or "Sybase SQL Server", as they are practically the same thing. Except Sybase actually runs in non-MS platforms!

    I hope your employer is not reading this, as MS SQL Server and Sybase SQL Server parted completely in... 1998 with the introduction of SQL Server 7.0

    I still work with both every day, and they're enough alike that I occasionally get confused. Compared with Oracle, mySQL, or Postgres, they're extremely close.

  • (cs) in reply to kswanton
    kswanton:
    One of the questions was 'How would you detect if you had a circular reference in a linked list?' I responded that you'd have to use some type of a hash table and iterate over the list - at each element, you'd need to check the hash table to see if you'd ever seen that element before - if you had, there is a circular reference, if not, add it to the hash and continue.

    The interviewer kinda smirked at me and said something along the lines of 'Well that is not efficient - is there a more efficient way to do it' to which I responded 'Not that I can think of...'

    Depends on what you mean by efficient. This is more memory efficient:

    public boolean hasCycle() {
      long counter = 0;
      Node node = first;
      while ( node != null && ++counter != 0 ) {
         node = node.next;
      }
      return node != null;
    }

    but doesn't have the greatest worst-case execution time. If the list kept an internal record of size, this would be a lot easier.

    I'd guess that the best solution would be a special case of checking a graph for cycles. And I'd also guess your solution would be the best for a typical programmer to be expected to know.

  • (cs)
    • "Well, you state that you have years of experience on telecommunication. Is that right?"
    • "Yes sir, I do."
    • "Tell me more about your experience then"
    • "Well I... I, uhn, I watch 2 hours of TV everyday and I errrr... I make phone calls on average 3 times a day for the past 5 years..."
  • (cs) in reply to Sutherlands
    Sutherlands:
    kswanton:
    One of the questions was 'How would you detect if you had a circular reference in a linked list?' I responded that you'd have to use some type of a hash table and iterate over the list - at each element, you'd need to check the hash table to see if you'd ever seen that element before - if you had, there is a circular reference, if not, add it to the hash and continue.
    I said the same thing, except the question asked of me was something to the tune of "How would you find if you have a circular reference and where that reference begins." To that, I replied something similar to yours, and the interviewer asked me if I could think of anything else... to which i said "Not off the top of my head." The correct answer to the question you were asked is: Create 2 pointers, one that traverses the list one at a time, and one that traverses the list two at a time. If they are ever equal, you have a circular reference. If you encounter the end, you don't. However... that only works when you're not trying to find the beginning of the list... which my interviewer decided to add on to the question. (The actual question is from what Google made up for one of their interviews when they were hiring, btw)
    I had someone ask me that. I also came up with the hash-solution. They responded with: what if the list is infinitely long? Figuring that this guy was an arrogant jerk for whom I no longer wished to work, I said: If you've got an infinite amount of data in a list, then your machine must have an infinite amount of memory in it, in which case it can handle an infintely large hash map. Then I laughed and walked out on him without another word.
  • (cs) in reply to Markp
    Markp:
    kswanton:
    One of the questions was 'How would you detect if you had a circular reference in a linked list?'...

    Depends on what you mean by efficient. ... I'd guess that the best solution would be ...

    Personally, I believe the best real-world solution is to make sure you don't insert the duplicate entry BEFORE doing the insert (maybe a linked list isn't the best choice if you don't want dups), but stupid interview questions warn you about the idiot in front of you, and for that I am grateful.

  • (cs) in reply to diaphanein
    diaphanein:
    For instance, in C#, here's an example of a finally block that'll never execute, even without pulling the plug from your computer. The only output will be "Before fail fast":
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace FailFast
    {
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			try
    			{
    				Console.WriteLine("Before fail fast");
    				Environment.FailFast(null);
    				Console.WriteLine("After fail fast");
    			}
    			finally
    			{
    				Console.WriteLine("in finally block");
    			}
    		}
    	}
    }
    

    Environment.FailFast is a method implemented on the C# runtime environment object and is specifically designed to fail without executing try-finally blocks (or finalizers, for that matter). That makes it a special case.

    Besides: as far as I can tell the method only came into being with the .NET 2.0 framework, whereas the article reflects on the .NET 1.0 days...

  • (cs) in reply to Sutherlands
    Sutherlands:
    The correct answer to the question you were asked is: Create 2 pointers, one that traverses the list one at a time, and one that traverses the list two at a time. If they are ever equal, you have a circular reference. If you encounter the end, you don't. However... that only works when you're not trying to find the beginning of the list... which my interviewer decided to add on to the question. (The actual question is from what Google made up for one of their interviews when they were hiring, btw)

    I'm not grokking this. Is there an explanation somewhere of how that would work?

  • (cs) in reply to snoofle
    snoofle:
    I had someone ask me that. I also came up with the hash-solution. They responded with: what if the list is infinitely long? Figuring that this guy was an arrogant jerk for whom I no longer wished to work, I said: If you've got an infinite amount of data in a list, then your machine must have an infinite amount of memory in it, in which case it can handle an infintely large hash map. Then I laughed and walked out on him without another word.
    The infinite memory chips overheat until they melt, now what do you do?
  • (cs) in reply to Dave
    Dave:
    Jason Bock:
    Holy crap, DON'T catch the general exception type!

    As long as you rethrow its not the end of the world.

    You just described the default behavior for a certain "custom" library I'm forced to use. Somewhere inside the thing, a simple method to get a connection from a DataSource throws an Exception, instead of the more manageable SQLException. Gaaah!

  • dzurn (unregistered)

    Wait a second ... "Min" ... "Min"... Minuet?!

    This is just an elaborate holodeck fantasy!

  • Goplat (unregistered)

    There's nothing better than a hash table? How about the tortoise-and-hare algorithm?

    int hasCycle(node *first) { node *t = first; node *h = first; do { if (!h) return 0; h = h->next; if (!h) return 0; h = h->next; t = t->next; } while (t != h); return 1; }

  • (cs) in reply to Alex Papadimoulis
    Alex Papadimoulis:
    ... but to expand on that, from a code perspective, if you're lucky enough to have an underlying transactional system, it's like this:

    try { StartTransaction(); DoStuff(); } catch { RollbackTransaction(); } finally { CommitIfNotRolledBack(); }

    The underlying transaction system will auto-rollback if it never gets committed or rolledback. However, the real problem occurrs when someone doesn't have an underlying transactional system.

    try { ProcessAllRecords(); } catch //(or a conditional finally) { UndoAllProcessing();
    }

    If ProcessRecords() is not designed to be re-entrant, then you're pretty much screwed if an error occurs and UndoAllProcessing() never is run.

    To make matters worse, these problems compound themselves, so the second time you run the program, the un-catchable exception occurs again and further corrupts the underlying data.

    Finally should be used for things like memory cleanup so you don't end up with leaks, etc. If the program never hits that kind of finally block, it's OK, since the whole thing has crashed and burned already, and memory leaks are the least of your worries.

    Yeah, but not using a transactional system is a major WTF in itself! That was the reason I was infuriated when reading the MySQL 3.x documentation, and reading "Transactions are for losers, we don't support it, we can do all of that with LOCK TABLES!" or something along those lines.

    I migrated all my stuff back to PostgreSQL after reading that. Mind you, there was already Sleepycat BDB and InnoDB support, but I just couldn't bear with the idea of using a DBMS built by people who think transactions are not critical. Kind of like building a big ship with no life-rafts because "we don't need them" ... oh wait, somebody did that already.

  • (cs) in reply to Camel Chase
    Camel Chase:
    Also a finally gets executed no matter what Exception hits.

    Consider:

    		try {
    			db.begin;
    			// do Stuff
    			Object o = null;
    			o.getClass(); // NullPointerException
    			
    			db.commit(); 
    			db.close(); // <--Problem
    			db = null;
    		} catch (NumberFormatException nfe) {
    			db.rollback();
    			db.close;
    			db = null;
    			// return error
    		} finally {
    			// free the db handle.
    			if (db != null) {
    				try {db.rollback(); db.close();} catch (Exception e) {}
    			}
    		}
    

    Your code is probably wrong (not cxhecking for null), but it doesn't chew up your db handles.

    kthxbye.

    If your close() function can fail, you're doing it wrong. Any "finalising" actions, such as destructors are not supposed to ever fail. Just call close() in finally {}.

  • (cs)

    Does Min know Max?

  • Ryeen (unregistered)

    I believe their faces turned white after continuing to argue when they asked you to move on. I don't see how arguing with an interviewer is very productive and might be a good time to let trivialities slide.

  • diaphanein (unregistered) in reply to Ragnax
    Ragnax:
    Environment.FailFast is a method implemented on the C# runtime environment object and is specifically designed to fail without executing try-finally blocks (or finalizers, for that matter). That makes it a special case.

    Besides: as far as I can tell the method only came into being with the .NET 2.0 framework, whereas the article reflects on the .NET 1.0 days...

    Ok:

    System.Diagnostics.Process.GetCurrentProcess().Kill();
    

    Is that 1.0 enough for ya? Point is, unless you write it, you can't be sure what your call will do.

    And special case(s) or not, it still invalidates the assertion that the final block always executes.

  • secundum (unregistered) in reply to ok new as
    ok new as:
    so hawt was her not het mom
    I have all of these technologies listed on my resume, too.
  • Franz Kafka (unregistered) in reply to Andrew
    Andrew:
    The arguments over try...catch...finally remind me of a story about the Java finalize() method. This mehod has far worse indeterminant behavoir than try...catch...finally.

    We had an otherwise brilliant programmer, with a C/Perl/CGI background but not Java. He even had a Master's degree in computer science.

    He was tasked with writing a JSP webapp for the company. The application usually ran fine, but occasionally it randomly executed some code.

    After much discovery, he found out that his AppClass.finalize() also overrode the Object.finalize() method. The garbage collector was running his method at random intervals.

    Well duh... finalize is for cleaning up objects before you kill them. I'd use it too, for network connections and stuff, but it isn't guaranteed to run.

  • (cs) in reply to Alex Papadimoulis
    Alex Papadimoulis:
    try { StartTransaction(); DoStuff(); } catch { RollbackTransaction(); } finally { CommitIfNotRolledBack(); }
    I prefer

    try { StartTransaction(); DoStuff(); CommitTransaction(); } catch { /* handle the exception */ } finally { RollBackIfNotCommitted(); }

    since you only need one commit and one rollback in total - usually in C# I just set the variable I used for the transaction object to null and call it's rollback method in the finally block only if it isn't null.

    np: Meat Beat Manifesto - Radio Babylon (Beach Blanket Bimboland Mix) (Auntie Aubrey's Excursions Beyond The Call Of Duty Part 2 (Disc 2))

  • Uncle Paul (unregistered)

    1.) Hire Min. 2.) ??????? 3.) Profit!

  • Eam (unregistered) in reply to danixdefcon5
    danixdefcon5:
    Dave:
    Jason Bock:
    Holy crap, DON'T catch the general exception type!

    As long as you rethrow its not the end of the world.

    You just described the default behavior for a certain "custom" library I'm forced to use. Somewhere inside the thing, a simple method to get a connection from a DataSource throws an Exception, instead of the more manageable SQLException. Gaaah!

    Easy now. If that's how it works when the library re-throws, they're not really re-throwing, they're creating a new exception.

    It sounds like you're using .NET, so you should use: try {...} catch (Exception) { ...; throw; }

    Not: try {...} catch (Exception e) { ...; throw e; }

  • Crabs (unregistered) in reply to Brian
    Brian:
    Wow, alot of people don't understand try/catch/finally here. It makes no sense to put a return statement in your finally block. If you think it does then you miss the point of finally.

    I agree with you. Finally should be used to do things that need to get done after either your try or your catch finished. Something like this:

    SqlConnection sql = new SqlConnection(); try{ sql.Open(); SqlCommand crapCommand = new SqlCommand("THIS IS A CRAP SQL CALL", sql); crapCommand.ExecuteReader(); //fails return 1; } catch{ return 0; //this ends up happening } finally{ sql.Close(); //this is what finally is for. otherwise your connection stays open foreverz }

    finally happens after the return statement. You should never have a return statement in your finally, as that's just weird. I'm sure it works somehow, but it's just not right.

Leave a comment on “My Tales”

Log In or post as a guest

Replying to comment #:

« Return to Article