Exception Handling in Python - Detailed
Notes
1. What is an Exception?
An exception is an error that occurs during program execution. It interrupts normal flow.
Example:
print(10/0)
2. Why Exception Handling?
• Prevents program crash
• Improves reliability
• Handles errors gracefully
• Helps debugging
3. Types of Errors
Syntax Error:
if True
print('Hello')
Runtime Errors:
ZeroDivisionError, ValueError, TypeError, FileNotFoundError
4. Try-Except Block
Syntax:
try:
pass
except:
pass
Example:
try:
num = int(input())
print(10/num)
except:
print('Error')
5. Specific Exceptions
try:
num = int(input())
print(10/num)
except ZeroDivisionError:
print('Cannot divide by zero')
except ValueError:
print('Invalid input')
6. Else Block
Runs if no exception:
try:
x = 10/2
except:
print('Error')
else:
print('Success')
7. Finally Block
Always executes:
try:
f = open('[Link]')
except:
print('Error')
finally:
print('Done')
8. Multiple Exceptions
try:
x = int('abc')
except (ValueError, TypeError):
print('Error')
9. Exception as Variable
try:
x = 10/0
except Exception as e:
print(e)
10. Raising Exceptions
age = -1
if age < 0:
raise ValueError('Invalid age')
11. Custom Exceptions
class MyError(Exception):
pass
try:
raise MyError('Custom error')
except MyError as e:
print(e)
12. Nested Try
try:
try:
x = int(input())
except ValueError:
print('Invalid')
except:
print('Outer error')
13. File Handling with Exceptions
try:
with open('[Link]') as f:
print([Link]())
except FileNotFoundError:
print('File not found')
14. Common Exceptions
ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, FileNotFoundError
15. Best Practices
• Catch specific exceptions
• Use finally for cleanup
• Avoid deep nesting
• Provide meaningful messages
16. Real-Time Example
try:
filename = input('Enter file: ')
with open(filename) as f:
print([Link]())
except FileNotFoundError:
print('File not found')
except Exception as e:
print('Error:', e)
finally:
print('Finished')