What is Exception ?
Lesson 1 of 16 in Coddy's Exception Handling in Python course.
Let's assume, your code is syntactically correct. So it will start execution. If it encounters an unexpected situation during the execution like running out of memory, python interpreter will raise an error. These errors detected during execution are called Exceptions.
Example 1
a = 10
b = 'Hii'
print(a + b) #TypeError
print("Rest of Code")In above Example, we tried to add integer to string. This is not allowed in python.
For addition, both operands should be of same type. Hence, python stopped execution and raised TypeError.
Example 2
MY_NAME = 'Mike'
print(my_name) #NameErrorIn above Example, we printed a variable my_name which does not exist. So python raised a NameError Exception.
note 1 : Python is case sensitive language. i.e 'MY_NAME' and 'my_name' are different.
note 2 : Above both programs are syntactically correct.
Challenge
EasyClick on Run Code and you will see important code isn't get executed in case of ZeroDivision. It's because of sudden termination of program due to Exception.
Try it yourself
def Division(num1, num2):
print("Hello World")
#divide by 0 will cause ZeroDivision Exception
print(num1/num2)
#Below statement won't be executed
print("This Code must be executed ")All lessons in Exception Handling in Python
4Customization/best practices
Customize Tracebacks