Kevin Yu wrote:
is it a bad programming design to throw exception in the try block then
catch it??
Here are some guidelines that i have formulated after having tried
different strategies of exceptions:
Don't use exceptions to indicate errors you expect to occur.
Don't throw exceptions to "break" the program flow to a specific
catch-handler (goto):
try {
...
if ( unexpectedSitua tion )
throw new UnexpectedSitua tion();
...
} catch ( UnexpectedSitua tion ) {
// this is a complicated way to do goto
}
But if an unhandled exceptional situation occurs, then do what you would
normally do, for eample:
Stream s = new Stream("x");
try {
byte[] data = new byte[4];
int read = 0;
while ( read < data.Length ) {
int r = s.Read(data, read, data.Length - read);
if ( r == 0 )
throw new ParseError("Str eam ended before data could be read");
}
return data;
} catch ( InvalidOperatio nError ) { // unrelated to ParseError
// Reading failed!
} finally {
s.Close();
}
NOTE: you could use: "using (Stream s = new Stream("x")) { ... }"
instead of try/catch.
It is often good to write the code to have minimal try/catch-blocks, for
example if there is a risk that dict[key] may not be a Foo:
Foo foo = (Foo)dict[key];
try {
foo.f(...);
} catch ( FooProcessingEx ception ) {
... // sensible error handler
}
instead of:
try {
((Foo)dict[key]).f(...);
} catch ( FooProcessingEx ception ) {
... // sensible error handler
}
So that error-handling is narrowly applied to the code that is expected
to expose the error.
In general: only catch if you can actually do anyting to remedy the
error, or is at the top of the call-stack. A possible exception is
catching for logging and retrow:
try {
f(...);
catch ( Exception e ) {
Log(e);
throw;
}
--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music:
http://ungdomshus.nu <=-