Key Takeaways: Exception Handling

  1. Exceptions separate normal logic from error handling. The try section contains the happy path; the except section handles failures. This produces code that is cleaner in both paths — normal logic is not cluttered with error checks, and error handling is not scattered throughout the code.

  2. try..except catches exceptions; try..finally guarantees cleanup. These serve different purposes and are often used together. Use try..except when you can handle an error. Use try..finally when you have resources to release.

  3. The Create-Try-Finally pattern is non-negotiable. Every time you create an object or open a resource, immediately start a try..finally block and put the cleanup (Free, CloseFile, etc.) in the finally section. This is how professional Pascal code prevents resource leaks.

  4. Catch specific exceptions, not generic ones. Catching Exception is almost always too broad. Catch EConvertError, EInOutError, ERangeError, etc. — the specific exception that represents the specific failure you can handle. Order handlers from most specific to most general.

  5. Never swallow exceptions. An empty except block — or one that catches and ignores errors — is one of the most dangerous patterns in programming. It hides bugs, corrupts data silently, and makes debugging nearly impossible. If you catch an exception, do something meaningful with it.

  6. Custom exception classes make your code professional. Define a base exception for your application and derive specific exceptions from it. Add properties to carry structured error data (field names, amounts, line numbers). This lets callers make intelligent decisions based on the specific error.

  7. Do not use exceptions for normal flow control. Exceptions should represent unusual, unexpected conditions. For expected situations (like "item not found in list"), use return values or conditional checks. Exceptions have overhead and using them for expected cases makes code harder to understand.

  8. The raise keyword signals errors; bare raise re-raises. Use raise ExceptionClass.Create(...) to create and throw an exception. Inside an except block, use raise with no arguments to pass the current exception to a higher handler.

  9. Document your exceptions. Pascal does not have checked exceptions (unlike Java), so it is your responsibility to document which exceptions each procedure can raise. Comments above procedures listing possible exceptions are essential for maintainability.

  10. Exception patterns transfer to every language. Python uses try-except-finally, Java uses try-catch-finally, C++ uses try-catch with RAII, C# uses try-catch-finally with using. The syntax varies; the concepts are identical. Master them in Pascal, and you have mastered them everywhere.