Programming
Posted on November 16, 2024
by Rajjit Laishram Admin
Updated on November 16, 2024
Types of Exception Handling in Python
# Syntax errors
print("hello world") # correct
print("hello world" # incorrect
# Indentation errors
if True:
print("hello world")
# NameError
a = 56
print(b)
# TypeError
a = 56
b = 'Hello'
result = b + a
print(result)
# ValueError
number = int("abc")
print(number)
In order to handle these errors, we use some exception handling functions:
# try-except
try:
result= 10/0
except ZeroDivisionError as newRes:
print(f'Error: {newRes}')
print('the result is', result)
# try-except (multiple)try:
value = int('abc')
except ValueError as ve:
print(f'Error: {ve}')
except ZeroDivisionError as res:
print(f'Error: {res}')
# try except elsetry:
result= 10/0except ZeroDivisionError as newRes:
print(f'Error: {newRes}')
else:
print('the result is', result)
# finallytry:
result= 10/5except ZeroDivisionError as newRes:
print(f'Error: {newRes}')
finally:
print('the result is', result)
print('this finally will always execute')
# custom
class customError(Exception):
pass
try:
raise customError("This is a custom exception")
except customError as e:
print(f'Custom error: {e}')
These are the codes as we have discussed in the tutorial video. If you haven't watched it already, please watch the full tutorial below:
Feel free to comment for any related questions and queries 😊
NOTE: You cannot delete your comment once added, so please don't post unnecessary comments!