Jump to content

  • Log In with Google      Sign In   
  • Create Account


- - - - -

goto statement inside catch


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 zz2   Members   -  Reputation: 265

Like
0Likes
Like

Posted 17 September 2007 - 03:00 AM

There was a discussion about goto statement at the beginning of this workshop and as I understood it goto is bad coding practice and should never be used. In chapter 25 author says that opening a file and reading from file should always be inside a try block but he doesn't tell much about how to handle exceptions. Working with files is very common and many times whole application cannot continue (or an operation) if some file cannot be read. As I have seen it is common in such cases to show a dialog that offers 3 options: retry (reading a file), cancel operation (if it can be done) and exit whole application. I find it hard to handle such situations without bloating my code too much. (It is annoying when error handling code is mixed with other code that executes logic operations) Using goto (like in example below) seems very convenient to me in such cases.
...
ReadFile:
try
{
//work with file
}
catch
{
...
//switch on dialog result 
case retry: goto ReadFile; //isn't it nice ;)
case endOperation: return;
case exit: exitApp();
...
}
...
Is this really that bad? Is there some common pattern for handling exceptions when working with files? PS: on page 229 author says that because Lenght and Position properties are of type long max file size is 9 terabytes. How did he get this number?

Sponsor:

#2 Josh Petrie   Moderators   -  Reputation: 3111

Like
0Likes
Like

Posted 17 September 2007 - 03:18 AM

Wrap the file IO in a do/while loop gated on the value of a "retry" boolean that is only set to true when the user elects to retry.

It's more idiomatic within the language context than goto.

#3 SiCrane   Moderators   -  Reputation: 9566

Like
0Likes
Like

Posted 17 September 2007 - 11:31 AM

You don't even need the extra boolean, you can use an infinite loop and break out at the end of the try.

for (;;) {
try {
// do stuff
break;
} catch {
// conditions; make retry a noop and it'll auto loop
}
}


As for the file size, I think he slipped a few digits. When I try calculating the maximum file size I get 9,223,372,036,854,775,807, which is a bit bigger than 9 TB.

#4 zz2   Members   -  Reputation: 265

Like
0Likes
Like

Posted 18 September 2007 - 02:43 AM

aha. thank you guys




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS