What are the Jump Statements in C#. break, Continue, return, goto and throw

Introduction

In C#, jump statements are used to transfer control from one part of code to another, either within loops, switch statements, or functions. C# provides several jump statements: break, continue, return, goto, and throw. Let’s go through each one in detail.

1. break Statement

The break statement is primarily used to exit a loop (for, while, do-while, or foreach) or a switch statement immediately. When a break statement is encountered, the control jumps to the first line of code following the loop or switch block.

Syntax

break;

2. continue Statement

The continue statement is used within loops to skip the current iteration and jump to the next iteration of the loop. Unlike break, it does not exit the loop; it simply skips to the next cycle of the loop.

Syntax

continue;

3. return Statement

The return statement is used in methods to end the execution of the method and optionally return a value to the calling method. In void methods, return simply exits the method without a value. In methods with a return type, it must include a value to return.

Syntax

return;          // For void methods
return value;    // For methods that return a value

4. goto Statement

The goto statement allows you to jump to a labeled statement within the same method. It is often discouraged in structured programming as it can make code hard to follow, but it can be useful in certain cases, such as jumping out of deeply nested loops or switch statements.

Syntax

goto label;
...
label:
    // Code to execute after the jump

5. throw Statement

The throw statement is used to signal the occurrence of an exception, which is an error condition that can be handled using try-catch blocks. When you throw an exception, it interrupts the normal program flow and transfers control to the nearest exception handler that can handle that specific type of exception.

Syntax

throw new ExceptionType("Error message");

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top