VOOZH about

URL: https://www.geeksforgeeks.org/c/using-goto-for-exception-handling-in-c/

⇱ Using goto for Exception Handling in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Using goto for Exception Handling in C

Last Updated : 9 Apr, 2026

Exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. C doesn’t provide any specialized functionality for this purpose like other programming languages such as C++ or Java. However, In C, goto keyword is often used for the same purpose. The goto statement can be used to jump from anywhere to anywhere within a function.

Syntax:

Why Use goto for Exception Handling?

The goto statement in C provides a way to jump to a labeled part of the code. While generally discouraged in modern programming due to readability and maintainability concerns, goto can be a clean solution for error handling in specific scenarios like:

  • Cleaning up allocated resources.
  • Breaking out of nested loops or blocks.
  • Handling errors in a single exit path.

The following examples demonstrate the use of goto for exception handling in C:

Simulate try-catch Statements


Output
Exception: Division by zero is not allowed!

Handling Exception in File Processing


Output
Error opening file

Limitations of goto in Exception Handling

Though it works fine, goto have some limitations as compared to the specialized exception handling structures.

  • Overuse can make the code harder to follow especially in larger codebases.
  • Misuse of goto may lead to bugs or spaghetti code.
  • Techniques like returning error codes or using modern C libraries (e.g., setjmp and longjmp) can sometimes be better.
Comment