Professional Documents
Culture Documents
Exception
Exception
Exception
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()
except(IOError) as e:
print(e)
except(ArithmeticError) as e:
print(e)
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)
finally:
print("success")
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)