Python Exception Handling: A to Z (Beginner to Advanced)
An exception is an error that occurs during the execution of a program. When Python encounters an error, it stops execution and throws an exception. If not handled, the program will crash. π―β οΈπ
Real-Life Analogy: Think of a vending machine. If you try to insert a torn currency note, it rejects it and shows an error. Similarly, Python "throws" an error when something unexpected happens. π₯€πΈπ«
SyntaxError
: Incorrect Python syntax.ZeroDivisionError
: Dividing a number by zero.TypeError
: Performing an operation on incompatible data types.ValueError
: Passing the wrong value to a function.FileNotFoundError
: Trying to open a non-existent file.IndexError
: Index out of range in a list.try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
try:
amount = int(input("Enter withdrawal amount: "))
print("Dispensing $", amount)
except ValueError:
print("Invalid input! Please enter a number.")