I've been wondering this for a while now; why is it that using a semi-colon ;
instead of an empty block {}
is not always valid? It works when using it on statements like while
, for
, if
, else
etc. But it does not work for try
, catch
, finally
and delegate
(probably a less useful to leave empty).
So doing something like this would be valid:
while(shouldIWait()); // This is normal
try {
doThing(); // Might throw an exception
} catch { } // Ignore the exception
But this would not:
try {
doThing(); // Might throw an exception
} catch; // Syntax error!
From my understanding a semi-colon can always be used instead of an empty block. Why is this limited to certain statements? Is there a real difference between the usage of { }
and ;
behind statements?
In some case a block of code is optional, in some case it is required.
In case of a method of a class or struct, a block of code is required (unless it is an abstract or partial method).
In case of a catch, a block of code (to handle the exception) is also required. Creating an empty catch-block is considered bad programming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With