Exception Handling in Python
Study Notes
Introduction
Exceptions are errors that occur during a Python program's execution, leading to unexpected
output or abnormal behavior
They arise from syntax errors, runtime errors, or logical errors in the code
Python exceptions are automatically triggered but can also be forcefully triggered and handled
via code
Exception handling is a crucial aspect of Python programming
Syntax Errors
Syntax errors, also known as parsing errors, are detected when the rules of the programming
language are violated
The interpreter does not execute the program until syntax errors are corrected
Python displays the error name and a description when a syntax error occurs in shell mode
When running a program in script mode, a dialog box appears with the error details
Exceptions
Exceptions can occur even if the syntax is correct; for example, trying to open a non-existent file
or dividing by zero
Exceptions disrupt the normal execution of a program
An exception is a Python object that represents an error, and an exception is "raised" when an
error occurs
Programmers must handle exceptions to prevent abnormal program termination
Programmers should anticipate potential errors and include code to handle them
Built-in Exceptions
Commonly occurring exceptions are predefined in the compiler/interpreter as built-in
exceptions
Python's standard library offers built-in exceptions for common errors, providing standardized
solutions
When a built-in exception occurs, the corresponding exception handler code executes,
displaying the reason and exception name
Common Built-in Exceptions
SyntaxError: Raised when there is an error in the Python code's syntax
ValueError: Raised when a method or operation receives an argument with the correct data
type but an inappropriate value
IOError: Raised when a specified file cannot be opened
KeyboardInterrupt: Raised when the user interrupts program execution with Delete or Esc
ImportError: Raised when a requested module definition is not found
EOFError: Raised when the end of a file is reached without reading data via input()
ZeroDivisionError: Raised when the denominator in a division is zero
IndexError: Raised when a sequence index is out of range
NameError: Raised when a local or global variable name is not defined
IndentationError: Raised due to incorrect indentation in the code
TypeError: Raised when an operator receives a value of an incorrect data type
OverflowError: Raised when a calculation exceeds the maximum limit for a numeric data type
Raising Exceptions
The Python interpreter raises (throws) an exception when an error is detected
Exception handlers are designed to execute when a specific exception occurs
Programmers can forcefully raise exceptions using the raise and assert statements
Raising an exception interrupts the normal program flow, transferring control to the exception
handler code
The raise Statement
The raise statement is used to throw an exception
The syntax is raise exception-name[(optional argument)]
The argument is typically a string displayed when the exception is raised
Errors detected can be built-in or user-defined exceptions
The assert Statement
Used to test an expression in code
If the expression is false, an exception is raised
Primarily used at the beginning of a function or after a function call to validate input
The syntax is assert Expression[, arguments]
If the expression is false, an AssertionError is raised, which is handled like other exceptions
Handling Exceptions
Programmers must handle exceptions to prevent abrupt program termination
This is achieved by writing additional code to provide messages or instructions, known as
exception handling
Need for Exception Handling
Exception handling captures runtime errors and prevents program crashes
Python categorizes exceptions for specific handlers
Exception handlers separate main logic from error detection and correction code
The compiler/interpreter tracks the error's location
Process of Handling Exceptions
When an error occurs, the interpreter creates an exception object with details like type, file
name, and position
This object is handed to the runtime system to find suitable handling code; this is "throwing" an
exception
Control jumps to the exception handler, abandoning remaining statements
The runtime system searches for an exception handler, checking the current method and calling
methods recursively (call stack)
Executing a suitable handler is known as "catching" the exception
If no handler is found, the program stops
Catching Exceptions
An exception is "caught" when code designed to handle it is executed
Exceptions are caught in a try block and handled in an except block
Suspicious code lines are placed in a try block, followed by an except block containing code to
handle possible exceptions
try...except Block
The syntax is:
try:
# program statements where exceptions might occur
except [exception-name]:
# code for handling the exception-name error
If an exception occurs, the try block stops, and control transfers to the except block
Multiple except Clauses
Multiple except blocks can handle different types of errors for a single try block
When an exception is raised, the matching except block is executed
If no match is found, the program terminates
except Without Specifying an Exception
An except clause without a specified exception can handle any unhandled exception
It should be the last except clause in the try...except block
try...except...else Clause
An optional else clause can be used with try...except
If no exception is raised in the try block, the statements in the else clause are executed
finally Clause
An optional finally clause can be used with a try statement
Statements inside the finally block always execute, regardless of whether an exception occurred
Commonly used to close file objects or release resources
If used, finally should be placed at the end of the try clause, after all except blocks and
the else block
Recovering and Continuing with finally
If an error is detected and an exception is thrown, the appropriate except block handles the
error
If the exception is unhandled, it is re-raised after the finally block executes
After the finally block, Python transfers control to a previously entered try block or a higher-
level exception handler