... ReadFile: try { //work with file } catch { ... //switch on dialog result case retry: goto ReadFile; //isn't it nice ;) case endOperation: return; case exit: exitApp(); ... } ...
goto statement inside catch
Started by zz2, Sep 17 2007 03:00 AM
3 replies to this topic
#1 Members - Reputation: 157
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.
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:
#3 Moderators - Reputation: 6662
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.
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.
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.






