-
Hajipur, Bihar, 844101
Python uses try...except blocks to handle errors gracefully. Instead of crashing the program, you can catch and manage errors during execution.
try:
x = 10 / 0
except:
print("An error occurred")
✅ Output: An error occurred
This prevents the program from crashing due to division by zero.
You can catch specific types of errors like ZeroDivisionError
, ValueError
, etc.
try:
num = int("abc")
except ValueError:
print("Invalid input")
Handle different exceptions separately:
try:
x = int("10")
y = 10 / 0
except ValueError:
print("Invalid conversion")
except ZeroDivisionError:
print("Can't divide by zero")
The else
block runs if no exception occurs.
try:
x = 5 + 3
except:
print("Error")
else:
print("No error occurred")
The finally
block always runs — whether there's an error or not.
try:
f = open("data.txt")
except:
print("File not found")
finally:
print("Done")
Use raise
to trigger an exception manually.
x = -5
if x < 0:
raise ValueError("Negative value not allowed")
Q1. Write a Python program to catch a ZeroDivisionError
and print a friendly message.
Q2. Write a Python program to use try...except
to handle input that can’t be converted to an integer.
Q3. Write a Python program to open a missing file and handle the FileNotFoundError
.
Q4. Write a Python program to create a function that raises a ValueError
when the input is negative.
Q5. Write a Python program to use try...except...else
to show a message when no error occurs.
Q6. Write a Python program to print "Always runs" using a finally
block.
Q7. Write a Python program to catch both IndexError
and KeyError
in separate except
blocks.
Q8. Write a Python program to use raise
to stop execution if a variable is empty.
Q9. Write a Python program to nest try-except
blocks and handle errors at both levels.
Q10. Write a Python program to use a try
block to take input and a finally
block to always close the process or display a message.
Q1: What is the purpose of try...except in Python?
Q2: Which keyword is used to catch exceptions?
Q3: What happens if an exception occurs and there's no except block?
Q4: Which block always executes, whether an error occurs or not?
Q5: What does the else block in try...except do?
Q6: What exception is raised for invalid integer conversion?
Q7: Which keyword is used to manually trigger an exception?
Q8: What does ZeroDivisionError mean?
Q9: Can you have multiple except blocks in Python?
Q10: Which block is optional in try...except structure?