## Use traceback built-in module for printing Tracebacks
import traceback
## Example 1: Catching specific errors
try:
a = 10
a = "this" + a
except (TypeError):
print("TypeError occurred") # TypeError occurred
# printing traceback
traceback.print_exc() # TypeError: can only concatenate \
# str (not "int") to str
## Example 2: Excepting multiple errors
try:
a = {}
print(a["some_key"])
print("This will not execute")
except (TypeError, KeyError) as e:
# printing the exception class name
print(f"{e.__class__.__name__} has occurred") # KeyError \
# has occurred
## Example 3: Catch any exception with 'Exception' class, it is base class of
# all exceptions, let's cause stackoverflow/RecursionError in python
# below is a user defined function, we'll learn about functions in next chapter
def my_fun():
try:
my_fun()
except Exception as e:
print(e.__class__) # <class 'RecursionError'>
# printing the exception
print(e) # maximum recursion depth exceeded
my_fun()
try:
a = 20 + 20 - 20
a = 20 / a
except Exception as e:
print(e.__class__)
print(e)
else:
# This optional block executes if no exception was raised.
print("else block executed") # else block executed
finally:
# Finally, it's finally, which will always execute.
print("finally block executed") # finally block executed
## Example 1: Creating a simple exception
class MyException(Exception):
pass
try:
raise MyException
except MyException:
print("My Exception was raised") # My Exception was raised
## Example 2: Raise a large value exception in pow()
# create a NumberTooLargeException exception
class NumberTooLargeException(Exception):
def __init__(self, message):
self.message = message
# this is message will be shown when the exception is printed
def __str__(self):
return f"NumberTooLargeException: {self.message}"
# a function to calculate power of a number given base and exponent
def calculate_pow(base_num, exp_num):
try:
if base_num > 100 and exp_num > 10:
raise NumberTooLargeException(
"base & exp are too large, numbers should be below 100 & 10"
)
elif base_num > 100:
raise NumberTooLargeException(
"base is too large, number should be below 100"
)
elif exp_num > 10:
raise NumberTooLargeException(
"exp is too large, number should be below 10"
)
print(pow(base_num, exp_num))
except Exception as e:
print(e)
# now calling the function with different values
calculate_pow(10, 2) # 100
calculate_pow(100, 2) # 10000
calculate_pow(100, 200) # NumberTooLargeException: exp is too large, \
# number should be below 10
calculate_pow(1000, 20) # NumberTooLargeException: base & exp are too large, \
# numbers should be below 100 & 10