Exception

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

Python Exception Handling:

* It is used to handle the runtime errors.


* It maintained the normal flow of the application
* Exception- abnormal conditions
* It's base class is Exception -predefined base class

blocks:
1. try: - source code everything with in try block
throw -raise
2. except: - it checks the exception is or not with in try block
3. finally: - enclose the code (Exception).

Ex:
ValueError
ArithmeticError

try:
x=100
y=200
print("Add=",x+y)
a=100
b=0
print("Divide",a/b)
except Exception as e:
print(e)

print("Welcome shiyam")

try:
a=100
b=0
print("Divide",a/b)
except Exception as e:
print(e)

try:
age=int(input("Enter the age:"))
if(age<18):
raise ValueError # predefined exception or throw
else:
print("Welcome to vote")
except ValueError:
print("Not Eligible to vote")

class sample:

def number(self):
try:
num=int(input("Enter the value:"))
if(num<0):
raise ValueError("This is a negative number.") # predefined
exception or throw
elif(num>=18):
print("Eligible to vote.")
else:
num+=10
print("value=",num)

except ValueError as e:
print(e) # display the Exception output

s=sample()
s.number()

#Nested try block:


try:
a=10/2
print("Divide=",a)
try:
fp=open("files.txt","r")

except(IOError) as e:
print(e)

except(ArithmeticError) as e:
print(e)

#Nested with multiple try block:


try:
try:
fp=open("files.txt","r")

except(IOError) as e:
print(e)
try:
a=10/0
print("Divide=",a)

except(ArithmeticError) as e:
print(e)

except Exception as e:
print(e)

# Multiple Exception at single line


try:
#a=10/2
#print("Divide=",a)
fp=open("files.txt","r")
except(ArithmeticError,IOError) as e:
print(e)
else:
fp.close()

finally:
print("success")

#custom Exception: or user defined Exception


#exception base class is Exception
class SalaryNotInRangeError(Exception): #Exception is a base class
# SalaryNotInRangeError is a user defined or custom Exception

def __init__(self,salary,message="Salary is not in until 15000 range"): # two


parameter

self.salary=salary
self.message=message
super().__init__(self.message) # for user defined message

try:
salary=int(input("Enter salary amount:"))
if salary<=15000:
raise SalaryNotInRangeError(salary)
else:
print("your salary amount:",salary)

except Exception as e:
print(e)

Assert:
The assert statement is used to continue the execute
if the given condition evaluates to True.
If the assert condition evaluates to False, then it raises the Assertion Error
exception with the specified error message.
Syntax:
assert condition [, Error Message]

try:

a=10
b=2
print("The value of a/b is:")
assert b!=0,"Zero Division Error" # for false condition
print(a/b)
except AssertionError as e:
print(e)

You might also like