Module 9: Exception Handling
What is Exception Handling?
Exception handling is a programming technique to gracefully manage errors that occur during a
program's execution, called exceptions. Instead of letting the program crash, you can "catch" and
respond to these errors, allowing the program to continue running or shut down gracefully.
Classification of Errors
This section should cover the broad categories of errors, like Syntax Errors and Logical Errors. The
existing content you provided is perfect for this:
In Python, there are two main categories of errors:
1. Syntax Errors (or Parsing Errors): These are errors detected by the Python interpreter before
the program runs. They are caused by incorrect syntax (e.g., a missing colon, a misspelled
keyword). You must fix these errors before the program can execute.
2. Logical Errors (or Exceptions): These are errors that occur during program execution. They
are caused by invalid operations, even if the code's syntax is correct. Exceptions are the type
of errors that can be "handled."
1. Syntax Errors
Syntax errors, also known as parsing errors, are mistakes in the structure of the code itself. These
are like grammatical errors in a language. The Python interpreter detects these errors before the
program even starts to run. If a syntax error is present, the program will not execute.
Common causes of syntax errors:
Missing or misplaced punctuation (e.g., a missing colon : at the end of a for loop or if
statement).
Misspelled keywords (e.g., typing prnt instead of print).
Missing parentheses, brackets, or quotation marks.
Example:
Python
# Missing colon at the end of the if statement
if x > 10
print("x is greater than 10")
When you try to run this code, Python will immediately stop and show a SyntaxError.
2. Logical Errors
Logical errors, also known as exceptions, are errors that occur during the program's execution.
Unlike syntax errors, the code is syntactically correct, but the operation it's trying to perform is
invalid. These errors are what you can "handle" using try...except blocks.
Common causes of logical errors:
Performing an impossible mathematical operation (e.g., dividing by zero).
Trying to access a file that doesn't exist.
Using an incorrect data type for an operation (e.g., trying to add a string to an integer).
Accessing a list index that is out of range.
Example:
Python
# This code is syntactically correct, but will cause a logical error
numbers = [1, 2, 3]
print(numbers[5]) # This will cause an IndexError because index 5 doesn't exist
In this case, the program will start to run but will crash with an IndexError when it reaches the
print statement.
Types of Exceptions
Python has many built-in exceptions that represent different kinds of errors. Here are some
common ones:
ValueError: Occurs when an operation receives an argument of the correct data type but an
inappropriate value. For example, trying to convert the string 'hello' to an integer.
TypeError: Occurs when an operation is applied to an object of an inappropriate data type.
For example, trying to add a string and an integer ('hello' + 5).
ZeroDivisionError: Occurs when you try to divide a number by zero.
FileNotFoundError: Occurs when you try to open or access a file that does not exist.
IndexError: Occurs when you try to access an index that is outside the bounds of a list or
tuple.
Syntax and Example
The primary tool for exception handling in Python is the try...except block.
1. The try...except Block
The basic syntax involves a try block for the code that might fail and an except block to handle
the specific error.
Syntax:
Python
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
Example:
Python
try:
# Code that might fail
num1 = int(input("Enter a number: "))
num2 = 10 / num1
print("Result:", num2)
except ValueError:
# Handles non-numeric input
print("Error: Invalid input. Please enter a valid number.")
except ZeroDivisionError:
# Handles division by zero
print("Error: You cannot divide by zero.")
2. The else Clause
The optional else block runs only if the code in the try block executes without any exceptions.
Syntax:
Python
try:
# Code that might raise an exception
except ExceptionType:
# Handle the exception
else:
# Code to run if no exceptions occurred
Example:
Python
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid number entered.")
else:
# This runs only if the conversion to int was successful
print("Success! The number is:", num)
3. The finally Clause
The optional finally block always runs, regardless of whether an exception occurred or not. It's
used for cleanup operations, like closing a file or a database connection, to ensure resources are
released.
Syntax:
Python
try:
# Code
except ExceptionType:
# Handle the exception
finally:
# Code that always runs
Example:
Python
file = None # Initialize to None
try:
file = open("[Link]", "r")
content = [Link]()
except FileNotFoundError:
print("File was not found.")
finally:
# This block ensures the file is closed, even if an error occurred.
if file:
[Link]()
print("Cleanup complete.")
END OF NOTES PREPARED BY [Link] B