What is Exception Handling?
· Exception
means the abnormal situation occurs at runtime and stop the execution of
program is called Exception.
· In
Python two type of error:
1.
Syntax
Error - As the name suggest this error is caused by wrong
syntax in the code. It leads to the termination of the program.
2.
Exception –
Exceptions are raised when the program is syntactically correct, but the code
resulted in an error. This error does not stop the exception of the program;
however, it changes the normal flow of the program.
3.
User-Define
Exception – User define exception means user can generate his
custom exception in python by inherited the Exception class.
Program 1) # Exception Create
a = int(input(“Enter the value of A:”))
print(“A:”, a)
Output = Enter the value of
A: 10 # Only Integer value
A: 10
Program 2) # Try and Exception
try:
a= int(input(“Enter
value of A: ”))
b= int(input(“Enter
value of B: ”))
c = a/b
print(“Answer: ”, c)
except Exception as e:
print(“Exception Caught: ”,e)
Output = Enter value of A:
10
Enter
value of B: 0
Exception
Caught: division by zero
Program 3) # Many Exception
try:
print(x) #we have not define variable x
except Name:
print(“Not define”)
except:
print(“Exception
Caught”)
Output = Not define
Program 4) # How to use else with except
try:
print(“Hello”)
except:
print(“Something went
wrong”)
except:
print(“Nothing went
wrong”)
Output = Hello, Nothing went
wrong
Program 5) # Finally Block – The block which run compulsory if error
occurs or not
try:
print(“Hello”)
except:
print(“Something went worng”)
finally:
print(“finally block”)
Output = Hello, finally block
Program 6) # User define Exception
class MyException(Exception):
Pass
c = 25
if c>5:
raise MyException(“Worng”)
Output = Error , Worng