Error Handling
ERROR HANDLING
Error handling allows a script to continue running even if an error occurs.
Common Built-in Exceptions
Examples of common errors in Python:
def woahhh() # SyntaxError
1 + name # NameError
5/0 # ZeroDivisionError
li = [1, 2, 3]
li[5] # IndexError
di = {'a': 1}
di['b'] # KeyError
Error Handling with
Try / Except / Else / Finally
- Blocks to handle errors gracefully.
-
Can write this try, except, else block for whole file to avoid errors
-
try → code that may cause an error
- except → handles specific errors
- else → runs if no error occurs
- finally → always runs, regardless of error
while True:
try: #if true print this
age = int(input('Enter your age:' ))
10/age
raise ValueError('Hey, Cut it out!!!') #shows errors to the user
#or raise Exception('hey cut it out')
except ValueError: #if an error print this, we can enter an error name to be specific
print('please enter a valid number')
except ZeroDivisionError:
print('Enter value more than Zero')
else: #to get out of loop
print('thank you')
break
finally:
print('ok, I am finally done')
#Finally block of code that will always execute, regardless of whether an exception occurs or not.
Error Handling for Functions
- You can catch multiple exceptions in one block using parentheses and the as keyword.
def sum(num1, num2):
try:
return num1 + num2
except (TypeError, ValueError, ZeroDivisionError) as error:
print (error)
print(sum(1,3)) # Output: 4
Can add many error in one and use AS keyword and name a variable