Exceptions in Python
Introduction
An exception is an event that occurs during the execution of a program that disrupts the normal flow of execution.
We use three keywords for this:
1) try: In this we need to write our code
2) catch: This block of code will be excuted in case there is an error in try block
3) finally: even if there is an error,this code will always excute
Exception Types
Import Error - If import attempt failes an Importerror will often be raised
Value error - occurs when a built-in function receives an argument that has the right type but an inappropriate value.
EOF error - Occurs When the function hits end of the file with out any data
Keyboard interuupt - Occurs when the user hits the interrupt key
IO error - Raised when an input or output operation fails
Name Error - Raised when tryimg to use an identifier with an invalid or unknown name
OS Error - This error raised when system level problem occurs
Value Error - Should be raised when a function or method receives an argument of the correct type,but the actual value that is invalid for some reason.
a = int(input("enter a no:"))
b = int(input("enter a no1:"))
c = a/b
print(c)
enter a no: 10
enter a no1: 0
Traceback (most recent call last):
c = a/b
ZeroDivisionError: division by zero
Using Exceptions(try-catch) we can achieve this
Write the program in try block and write the desired form of error in except block
a = int(input("enter a no:"))
b = int(input("enter a no1:"))
try:
c = a/b
except Exception as e:
print("exception")
else:
print(C)
finally:
print("Print finally block")
Output:
enter a no: 10
enter a no1: 0
exception
Print finally block