Key Takeaways: Exception Handling
-
Exceptions separate normal logic from error handling. The
trysection contains the happy path; theexceptsection 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. -
try..exceptcatches exceptions;try..finallyguarantees cleanup. These serve different purposes and are often used together. Usetry..exceptwhen you can handle an error. Usetry..finallywhen you have resources to release. -
The Create-Try-Finally pattern is non-negotiable. Every time you create an object or open a resource, immediately start a
try..finallyblock and put the cleanup (Free,CloseFile, etc.) in thefinallysection. This is how professional Pascal code prevents resource leaks. -
Catch specific exceptions, not generic ones. Catching
Exceptionis almost always too broad. CatchEConvertError,EInOutError,ERangeError, etc. — the specific exception that represents the specific failure you can handle. Order handlers from most specific to most general. -
Never swallow exceptions. An empty
exceptblock — 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. -
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.
-
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.
-
The
raisekeyword signals errors; bareraisere-raises. Useraise ExceptionClass.Create(...)to create and throw an exception. Inside anexceptblock, useraisewith no arguments to pass the current exception to a higher handler. -
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.
-
Exception patterns transfer to every language. Python uses
try-except-finally, Java usestry-catch-finally, C++ usestry-catchwith RAII, C# usestry-catch-finallywithusing. The syntax varies; the concepts are identical. Master them in Pascal, and you have mastered them everywhere.