0% found this document useful (0 votes)
2 views2 pages

Exceptions Example

The document provides examples of various Python exceptions, including StopIteration, SystemExit, ArithmeticError, AssertionError, AttributeError, IndexError, KeyError, NameError, and TypeError. Each exception is demonstrated with a code snippet that shows how to handle it using try-except blocks. The examples illustrate common programming errors and how to manage them effectively.

Uploaded by

outlooksinet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Exceptions Example

The document provides examples of various Python exceptions, including StopIteration, SystemExit, ArithmeticError, AssertionError, AttributeError, IndexError, KeyError, NameError, and TypeError. Each exception is demonstrated with a code snippet that shows how to handle it using try-except blocks. The examples illustrate common programming errors and how to manage them effectively.

Uploaded by

outlooksinet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

exceptions example

1.StopIteration

nums = iter([1, 2, 3])


try:
while True:
print(next(nums))
except StopIteration:
print("StopIteration: No more items in iterator.")

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")

You might also like