Exception Handling
When a program runs, sometimes errors can
occur (like dividing by zero or trying to open a file that doesn't exist).
These errors are called exceptions.
Exception Handling allows the program to
respond to errors gracefully instead of crashing.
Why Use Exception Handling?
- Prevents the program from crashing.
- Helps in debugging.
- Makes the program user-friendly.
Example Without Exception
Handling
a = int(input("Enter a number:
"))
b = int(input("Enter another number:
"))
print("Result:", a / b) #
If b = 0, program crashes!
If the user enters 0 for b, it shows:
ZeroDivisionError: division by zero
Using Try-Except to Handle Exceptions
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Result:", a / b)
except ZeroDivisionError:
print("You cannot divide by zero!")
Explanation:
- try block: Code that might cause an error.
- except block: Code that runs if an error occurs.
Example of ValueError
num = int(input("Enter a number:
")) # if user enters invalid value
‘abc’
CODE WITH TRY BLOCK
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a number.")
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Result:", a / b)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter valid numbers.")
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Division result is:", result)
finally:
print("This block always runs.")
- else: Runs if no error occurs.
- finally: Runs always, whether there’s an error or
not.
Handling Exception while Opening a File
EG: FileNotFoundError exception
handling for opening a user given filename
filename = input('Enter the file name to
read -: ')
fobj = open(filename, "r") # If file doesn't exist, it will crash
here
str = fobj.readlines() # Read all lines into a list
print(str)
fobj.close() # Close the file
CODE WITH TRY:
filename = input('Enter the file name to
read -: ')
try:
fobj = open(filename, "r")
str = fobj.readlines() # file
read & assigned to a variable
print(str)
fobj.close() # close only if file
is successfully opened
except FileNotFoundError:
print('There is no file named', filename)
IOError stands for Input/Output Error.
It occurs when an input/output operation fails,
such as:
- Trying
to open a file that doesn't exist
- Trying
to read/write to a file that cannot be accessed
Eg:
try:
file =
open("data.txt", "r")
# If file doesn't exist
content =
file.read()
print(content)
file.close()
except IOError:
print("An input/output error occurred.")
Common Run-Time Errors in
Python
| Error Type
| Cause |
| ------------------- |
------------------------------------------ |
| `ZeroDivisionError` | Division by 0 |
| `FileNotFoundError` | File not found |
| `ValueError`
| Wrong value (e.g. text in place of number) |
| `IndexError`
| Invalid index in a list or string |
| `TypeError`
| Operation on incompatible data types |
Comments
Post a Comment