Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a semi-colon instead of an empty block not always valid?

Tags:

syntax

c#

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?

like image 533
Mechazawa Avatar asked Oct 20 '22 15:10

Mechazawa


1 Answers

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.

like image 157
Martin Mulder Avatar answered Oct 24 '22 08:10

Martin Mulder