EXCEPTION HANDLING IN PYTHON
1.1 Introduction to Exception Handling
Exception Handling is a mechanism in Python used to detect and handle runtime errors
(exceptions) so that the program does not terminate abnormally. It helps display meaningful error
messages and improves program reliability.
1.2 Syntax Error
A Syntax Error is an error that occurs when the rules (syntax) of Python are violated. Python
detects these errors before execution starts.
Example: Missing colon, missing bracket, wrong indentation.
1.3 Exceptions
An Exception is an event or error that occurs during program execution and interrupts the normal
flow of instructions. Exceptions occur at runtime.
Example: Division by zero (ZeroDivisionError).
1.4 Built-in Exceptions
Built-in Exceptions are predefined exceptions provided by Python. Examples: ZeroDivisionError,
ValueError, TypeError, NameError, IndexError, KeyError, FileNotFoundError.
1.5 Raising Exceptions
Raising an Exception means deliberately generating an exception using the raise keyword when a
specific condition occurs.
Syntax: raise ExceptionName('Error Message')
1.6 Handling Exceptions
Handling Exceptions is the process of detecting and responding to runtime errors using try and
except blocks.
Syntax: try: risky code except: handling code
1.7 Finally Clause
The finally block always executes whether an exception occurs or not. It is commonly used for
cleanup operations such as closing files or database connections.
Quick Revision
Exception Handling → Handle runtime errors
Syntax Error → Error before execution
Exception → Error during execution
raise → Create an exception
try/except → Handle exceptions
finally → Always executes