Exceptions Example
Exceptions Example
1.StopIteration
2.SystemExit
import sys
try:
sys.exit("Exiting the program")
except SystemExit as e:
print("SystemExit:", e)
3.ArithmeticError
# ZeroDivisionError
try:
x = 10 / 0
except ZeroDivisionError:
print("ZeroDivisionError: Cannot divide by zero")
# OverflowError
try:
import math
print(math.exp(1000)) # Very large exponential
except OverflowError:
print("OverflowError: Number too large")
4.AssertionError
try:
assert 2 + 2 == 5
except AssertionError:
print("AssertionError: Expression is false")
5.AttributeError
try:
x = 5
x.append(3)
except AttributeError:
print("AttributeError: 'int' object has no attribute 'append'")
6.IndexError
try:
lst = [1, 2, 3]
print(lst[5])
except IndexError:
print("IndexError: List index out of range")
7.KeyError
try:
d = {'a': 1}
print(d['b'])
except KeyError:
print("KeyError: Key not found in dictionary")
8. NameError
try:
print(xyz)
except NameError:
print("NameError: Variable not defined")
9.TypeError
try:
print("2" + 2)
except TypeError:
print("TypeError: Cannot add string and int")