Real programs fail. Strong programs handle failure gracefully.
Error handling is what separates beginners from professionals.
An error is a problem that stops program execution.
print(10 / 0)
This causes a ZeroDivisionError.
try:
print(10 / 0)
except:
print("Something went wrong")
try:
x = int("abc")
except ValueError:
print("Invalid number")
try:
a = int(input("Enter number: "))
print(10 / a)
except ValueError:
print("Please enter a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
Runs only if no error occurs.
try:
num = int(input("Enter number: "))
except ValueError:
print("Invalid input")
else:
print("You entered:", num)
Always runs — error or no error.
try:
file = open("data.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found")
finally:
print("Program finished")
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
print(divide(10, 2))
print(divide(10, 0))
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
except:Error handling is not about avoiding errors. It is about controlling failures.
Next part: Modules & Packages.