Exception Handling in Python
Errors in a program can be categorized into following types
1. Compile Time Error: Errors that occur during the compilation of the program.
2. Run Time Error: Errors that occur while the program is running. Some of the example of run time error
are:
Division by Zero
Using of undefined variable
Trying to access a non-existing file
3. Logical Error: Errors in the program's logic, which do not produce errors but lead to incorrect results.
Some of the example of logical error are:
Giving wrong operator precedence
using wrong variable name for calculation
4. Syntax Errors: Mistakes in writing code that prevent the program from running. Some of the example
of syntax error are:
Incorrect Indentation
Misspelled a keyword
leaving out a symbol such as colon (:), parentheses [{()}] or comma (,).
5. Semantics Errors: Logic errors that produce unintended results.
Exception
An exception is a type of error that occurs during program execution.
Python generates an exception whenever an error is encountered.
Exceptions can be handled to prevent the program from crashing.
Error vs. Exception
Error: Any mistake or issue in the code.
Exception: An unexpected situation or error during program execution.
Exception Handling
Exception handling is the process of dealing with run-time errors.
It involves using 'try...except blocks to catch and handle exceptions.
Program without Exception Handling
Python Program to divide two numbers without exception handling
1. num1 = int(input("Enter first number"))
2.
3. num2 = int(input("Enter Second number"))
4.
5. result = num1 / num2
6.
7. print("Result:", result)
Output:
= RESTART: C:/Users/lenovo/AppData/Local/ Programs/Python/Python311/excephanding.py
Enter first number12
Enter Second number2
Result: 6.0
= RESTART: C:/Users/lenovo/AppData/Local/Programs/Python/Python311/excephanding.py
Enter first number12
Enter Second number0
Traceback (most recent call last):
File "C:/Users/lenovo/AppData/Local/Programs/Python/Python311/excephanding.py"
line 5, in <module>
result num1 / num2
ZeroDivisionError: division by zero
Program with Exception Handling
Python Program to divide two numbers with exception handling
1. num1 = int(input("Enter first number"))
2.
3. num2 = int(input("Enter Second number"))
4.
5.
try:
6. result = num1 / num2
7. 8. print("Result:", result)
9.
10.
11.
except ZeroDivisionError:
12.
print ("You Can not divide a number by Zero....")
13.
= RESTART: C:/Users/lenovo/AppData/Local/ Programs/Python/Python311/excephanding.py
Enter first number12
Enter Second number0
You Cannot divide a number by Zero....
Exception Handling in Python
Built-in Exceptions in Python
- Python provides various built-in exceptions that can be caught and handled using "try...except.
In Python, exceptions are a way to handle runtime errors and exceptional situations that can occur
during program execution. Python provides a variety of built-in exceptions that you can use to catch and
handle different types of errors. Here are some of the most commonly used built-in exceptions in
Python:
1. 'SyntaxError': Raised when there is a syntax error in your code.
2. 'IndentationError': Raised when there is an indentation error in your code, such as mismatched
indentation levels.
3. 'NameError': Raised when a local or global name's not found.
4. TypeError': Raised when an operation or function is applied to an object of inappropriate type.
5. ValueError': Raised when an operation or function receives an argument of the correct type but an
inappropriate value.
6. 'KeyError': Raised when a dictionary is accessed with a key that doesn't exist.
7. 'IndexError': Raised when trying to access an element at an invalid index in a sequence (e.g., list,
tuple).
8. 'FileNotFoundError': Raised when trying to open or manipulate a file that does not exist.
9. `IOError': Raised for I/O-related errors, such as when reading or writing to a file fails.
10. ZeroDivisionError': Raised when attempting to divide by zero.
11. AttributeError': Raised when an attribute reference or assignment fails.
12. 'ImportError': Raised when an import statement fails to find the module.
13. TypeError': Raised when an incorrect type is passed as an argument to a function or method.
14. 'AssertionError': Raised when an assert statement fails.
15. KeyboardInterrupt': Raised when the user interrupts the program (e.g., by pressing Ctrl+C).
16 EQFError: Raised when an input operation reaches the end of the file
17. ArithmeticError': A base class for numeric errors, including ZeroDivisionError and OverflowError.
18. 'FileExistsError': Raised when trying to create a file or directory that already exists.
19. 'FileNotFoundError': Raised when trying to access a file or directory that does not exist.
20. 'PermissionError': Raised when trying to perform an operation without the necessary permissions.
Handling Multiple Exceptions
In Python, you can handle multiple exceptions in the same program by using multiple except blocks
within a try block. Each except block is responsible for handling a specific type of exception.
Here's an example that demonstrates how to handle different exceptions:
1. def divide_numbers(a, b):
2. try:
3. result a/b
4. except ZeroDivisionError:
5. print("Error: Division by zero!")
10 except TypeError:
11. print("Error: Invalid data type!")
12. result = None
13. except Exception as e:
14 print (f"An unexpected error occurred: {e}")
15. result = None
16. finally:
17. print("Exception Handing in Python...")
18.
19. return result
20.
21. # Example 1: Division without error
22. result1 = divide_numbers(10, 2)
23. print("Result 1:", result1)
24.
25. # Example 2: Division by zero (ZeroDivisionError)
26. result2 = divide_numbers(5, 0)
27. print("Result 2:", result2)
28.
29. # Example 3: Invalid input value (ValueError)
30. result3 = divide_numbers(10, "2")
31. print("Result 3:", result3)
32.
33. # Example 4: Invalid data type (TypeError)
34. result4 divide_numbers("10", 2)
35. print("Result 4:", result4)
Output:
Exception Handing in Python...
Result 1: 5.0
Error: Division by zero!
Exception Handing in Python...
Result 2: None
Error: Invalid data type!
Exception Handing in Python...
Result 3: None
Error: Invalid data type!
Exception Handing in Python...
Result 4:
1
None
In this example, we have a divide_numbers function that performs division and handles multiple
exceptions:
ZeroDivisionError is raised when attempting to divide by zero.
ValueError is raised if the input values cannot be converted to numeric types.
TypeError is raised if the data types of the input values are incompatible with division.
The generic Exception block is used to catch any unexpected exceptions and display an error message.
Each exception type is handled separately, allowing the program to provide appropriate error messages
and perform cleanup operations for each case.
The finally Block
- The 'finally block contains code that must execute, whether or not an exception was raised in the try'
block.
- It ensures that certain actions are taken regardless of the outcome.
In Python, the finally block is an essential part of exception handling, working alongside the try and
except blocks. It allows you to define code that will execute regardless of whether an exception is raised
or not. This can be particularly useful for tasks such as closing files, releasing resources, or performing
cleanup operations to ensure that your program remains in a consistent state.
Here's the basic structure of a try...except...finally block in Python:
1. try:
2. #Code that may raise an exception
#41 except SomeException:
5. Handle the exception if it occurs
7. finally:
8. # Code that always runs, whether an exception occurred or not
9.
Finally Block Example
1. def divide_numbers(a, b):
2. try:
3. result = a/b
4 except ZeroDivisionError:
5. print("Error: Division by zero!")
6. result = None
76 finally:
8. print("Notes Exception Handling in Python Class 12...")
9. #This code will always run, even if an exception occurred or not
10.
11. return result
12.
13. #Example 1: Division without error
14. result1 divide_numbers(10, 2)
15. print("Result 1:", result1)
16.
17. # Example 2: Division by zero (error)
16. result2 divide_numbers(5, 0)
19. print("Result 2:", result2)
Output:
Result 1: 5.0
Error: Division by zero!
Result 2:None
In this example, the divide_numbers function attempts to divide two numbers. If a ZeroDivisionErroг
occurs (division by zero), it is caught in the except block. However, the finally block is executed in both
cases to perform cleanup operations.
Here are some key points to remember about the finally block in Python exception handling:
The finally block is optional but useful for ensuring that critical cleanup operations are
performed, even in the presence of exceptions.
The code inside the finally block will run regardless of whether an exception is raised or not. It is
guaranteed to execute.
You can use the finally block to close files, release resources, or perform any other necessary
cleanup tasks.
If there is a return statement in the finally block, it will override any return value set in the try or
except blocks. So be careful when using return within the finally block
Raising/Forcing an Exception
- You can raise exceptions manually using the 'raise keyword.
- Syntax: 'raise <exception>(<message>) (The exception should be a pre-defined built-in exception.)
Benefits of Exception Handling
Exception handling separates error-handling code from normal code.
It enhances code readability and clarity.
It promotes consistent error-handling practices.
It leads to clear, robust, and fault-tolerant programs.
Exception Handling in Python
File Operations
`seek() Used to change the position of the file pointer to a specific location.
- The file pointer is like a cursor indicating where data should be read or written in the file.
Syntax: 'f.seek(file_location) or 'f.seek(offset, from_what)
-0: Sets the reference point at the beginning of the file (default).
1': Sets the reference point at the current file position.
-'2': Sets the reference point at the end of the file.
tell() Tells the current position of the file pointer.
- In 'r' and 'w' mode, the file pointer is at the beginning of the file.
- In 'a' mode, the file pointer is at the end of the file when using 'tell().