Exception handling Concept in Python:-

44
Exception handling Concept in Python:-
Exception means unexpected run time error, which will be occurred during the execution of the program.
It is used to handle unexpected run time errors of the program to solve another program code interruption.
A project is a set of programs, if one program will be interrupted then the complete project will be destroyed hence we should always implement exception handling to protect program interruption in an application.
Python provides a try-except block to manage the exception block in the python program.
try block is used to represent code and except block will be used to write error message.
Exception handling is mandatory in all program codes hence we should always exception handling under python script.
Some Exceptions can be raised by hardware issues, software issues, network issues, permission issues, disk failures.
Basic Syntax of Exception on Python:-
1)   Only Try and Except:-
try:
   CODE BLOCK
   CODE BLOCK
except :
    ErrorMessage
2)   Try--Except with Classname
try:
   CODE BLOCK
   CODE BLOCK
except ExceptionClassname :
    ErrorMessage
3)   TRY with Multiple Except Block
try:
   CODE BLOCK
   CODE BLOCK
except ExceptionClass1 :
    ErrorMessage
except ExceptionClass2 :
    ErrorMessage
4)  TRY ---- EXCEPT ------ FINALLY
try:
   CODE BLOCK
   CODE BLOCK
except ExceptionClass1 :
    ErrorMessage
finally:
    Default block
5)   TRY ----  EXCEPT  ---- ELSE and Finally:-
try:
   CODE BLOCK
   CODE BLOCK
except ExceptionClass1 :
    ErrorMessage
else:
   Statements
finally:
    Default block
6)  TRY...... EXCEPT ---- ELSE:-
try:
   CODE BLOCK
   CODE BLOCK
except ExceptionClass1 :
    ErrorMessage
else:
    Default block


Example of Exception Handling:-
try:
  a=  int(input("enter first number"))
  b = int(input("enter second number"))
  c=a/b
  print(c)
except ZeroDivisionError ex:
  print ('denominator can not be zero")
How to Handle Multiple Exception in Program:-
try:
  a=  int(input("enter first number"))
  b = int(input("enter second number"))
  c=a/b
  print(c)
except ZeroDivisionError:
  print ('denominator can not be zero')
except ValueError:
  print ('enter only numeric value')  
print("Line1")
print("Line2")
...................................................................................................................................................
.....................................................................................................................................................
finally:-
It will be executed with exception and without exception means it is the default block that will be executed whenever an exception will be occurred or not.
try:
   statements
except Exception:
     Error Message
finally:
    Default Statement
It is used to provide acknowledgment or dispose of object data.
try:
  a=  int(input("enter first number"))
  b = int(input("enter second number"))
  c=a/b
  print(c)
except ZeroDivisionError:
  print ('denominator can not be zero')
except ValueError:
  print ('enter only numeric value')  
finally:
  print('finally')
   print("Line1")
print("Line2")
..................................................................
else:-  It is the opposite of except, if the exception will not occur and we want to do something then we can write code on the else block. It is the opposite of except block.
try:
  statements
  statements
except ExceptionClassname
  statements
  statements
else:
  statements
Example of Try..except--else --finally
try:
  a=  int(input("enter first number"))
  b = int(input("enter second number"))
  c=a/b
  print(c)
except ZeroDivisionError:
  print ('denominator can not be zero')
except ValueError:
  print ('enter only numeric value')
else:
  print("NOT ANY ERROR")  
finally:
  print('finally')
  
print("Line1")
print("Line2")
Note:- Exception is the base class for all type of Exceptions
try:
  a=  int(input("enter first number"))
  b = int(input("enter second number"))
  c=a/b
  print(c)
except Exception:
  print ('error')

else:
  print("NOT ANY ERROR")
finally:
  print('finally')
print("Line1")
print("Line2")
Complete Program of Exception Which Contain Try--except.
flag=True
count=0
while(flag):
 try:
  a = int(input("enter first number"))
  b = int(input("enter second number"))
  c=a/b
  print(c)
 except ValueError:
  print("enter only numeric")
 except ZeroDivisionError:
  print("denominator can not be zero")
 else:
  flag=False
 finally:
  count=count+1
  print("Number of attempt "+str(count))
Complete Example of Exception:-
c=0
s=''
try:
 a= int(input("enter first number"))
 b= int(input("enter second number"))
 c=a/b
 except ZeroDivisionError:
    s = 'Result is default'
    print("denominator can not be zero")
except ValueError:
    s='Result is default'
    print("Enter only numeric value")
else:
    s="Result is Accurate "
finally:
    print(s,c)

Sr.No.Exception Name & Description
1
Exception
Base class for all exceptions
2
StopIteration
Raised when the next() method of an iterator does not point to any object.
3
SystemExit
Raised by the sys. exit() function.
4
StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
5
ArithmeticError
Base class for all errors that occur for numeric calculation.
6
OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7
FloatingPointError
Raised when a floating-point calculation fails.
8
ZeroDivisionError
Raised when a division or modulo by zero takes place for all numeric types.
9
AssertionError
Raised in case of failure of the Assert statement.
10
AttributeError
Raised in case of failure of attribute reference or assignment.
11
EOFError
Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
12
ImportError
Raised when an import statement fails.
13
KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14
LookupError
Base class for all lookup errors.
15
IndexError
Raised when an index is not found in a sequence.
16
KeyError
Raised when the specified key is not found in the dictionary.
17
NameError
Raised when an identifier is not found in the local or global namespace.
18
UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has been assigned to it.
19
EnvironmentError
Base class for all exceptions that occur outside the Python environment.
20
IOError
Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
21
IOError
Raised for operating system-related errors.
22
SyntaxError
Raised when there is an error in Python syntax.
23
IndentationError
Raised when indentation is not specified properly.
24
SystemError
Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.
25
SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
26
TypeError
Raised when an operation or function is attempted that is invalid for the specified data type.
27
ValueError
Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
28
RuntimeError
Raised when a generated error does not fall into any category.
29
NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.


User define exception in Python:-

We can create our own exception classes to manage the exception-based program, Python uses class and object concepts to implement user-defined Exceptions.

Now I am creating Salary Exception where if the Salary will be less than` 10000 then it will raise an exception otherwise display a salary.


Syntax of User define an exception

class  Classname(Exception):
       pass



Example of exception:-

class SalaryException(Exception):
    pass

try:
 sal = int(input("Enter salary of employee"))
 if sal<10000:
    raise SalaryException
 else:
     print("Salary is "+str(sal))
    
except SalaryException:
    print("Salary should be above 10000")
What is the raise?
raise is a keyword that is used to call Exception, it is similar to the Java throw keyword.
ASSIGNMENTS of Exception handling:-
1)  Manage mark sheet program with all possible exception
2)  WAP to validate mobile number using the Exception?
3)  Create a program for addition, subtraction, multiplication, and division using multiple exception block.
4)  Create user-defined exceptions when student fees are>500000 otherwise display fees?
5)  Define 10 predefine exceptions with possible examples?
Tags

Post a Comment

44Comments

POST Answer of Questions and ASK to Doubt

  1. doubt-how to execute following code
    def foo():
    try:
    return 1
    finally:
    return 2
    k = foo()
    print(k)

    ReplyDelete
  2. doubt-sir if we write else after finally is it write or not
    try:
    1 / 0
    except:
    print('exception')
    else:
    print('else')
    finally:
    print('finally')

    ReplyDelete
  3. # Create user-defined exceptions when student fees are>500000 otherwise display fees?
    class FeesException(Exception):
    pass
    try:
    fees=int(input("enter fees of student"))
    if fees<500000:
    raise FeesException
    else:
    print("fees is "+str(fees))
    except FeesException:
    print("fees should be above 500000")

    ReplyDelete
  4. #Create a program for addition, subtraction, multiplication, and division using multiple exception block.
    try:
    a=int(input("enter value of a"))
    b=int(input("enter value of b"))
    c=a+b
    print(c)
    except ValueError:
    print("value should be numeric")
    try:
    a=int(input("enter value of a"))
    b=int(input("enter value of b"))
    c=a-b
    print(c)
    except ValueError:
    print("value should be numeric")
    try:
    a=int(input("enter value of a"))
    b=int(input("enter value of b"))
    c=a*b
    print(c)
    except ValueError:
    print("value should be numeric")
    try:
    a=int(input("enter value of a"))
    b=int(input("enter value of b"))
    c=a/b
    print(c)
    except ZeroDivisionError:
    print("denomentor not be zero")


    ReplyDelete
  5. 1-exception LookupError
    This is the base class for those exceptions that are raised when a key or index used on a mapping or sequence is invalid or not found. The exceptions raised are :
    KeyError
    IndexError
    try:
    a = [1, 2, 3]
    print (a[3])
    except LookupError:
    print ("Index out of bound error.")
    else:
    print ("Success")

    2-exception EOFError
    An EOFError is raised when built-in functions like input() hits an end-of-file condition (EOF) without reading any data. The file methods like readline() return an empty string when they hit EOF.
    Example :


    while True:
    data = input('Enter name : ')
    print ('Hello ', data)
    exception FloatingPointError
    3-A FloatingPointError is raised when a floating point operation fails.
    import math

    print (math.exp(1000))
    4-exception KeyError
    A KeyError is raised when a mapping key is not found in the set of existing keys.
    array = { 'a':1, 'b':2 }
    print (array['c'])
    5-exception MemoryError
    This error is raised when an operation runs out of memory.
    Example :def fact(a):
    factors = []
    for i in range(1, a+1):
    if a%i == 0:
    factors.append(i)
    return factors

    num = 600851475143
    print (fact(num))
    6-exception NameError
    This error is raised when a local or global name is not found. For example, an unqualified variable name.
    def func():
    print ans

    func()
    7-exception StopIteration
    The StopIteration error is raised by built-in function next() and an iterator‘s __next__() method to signal that all items are produced by the iterator.
    Example :
    Arr = [3, 1, 2]
    i=iter(Arr)

    print (i)
    print (i.next())
    print (i.next())
    print (i.next())
    print (i.next())
    8-A ZeroDivisionError is raised when the second argument of a division or modulo operation is zero.
    print (1/0)
    9-exception ValueError
    A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.
    Example :print (int('a'))
    10-exception TypeError
    TypeError is raised when an operation or function is applied to an object of inappropriate type
    arr = ('tuple', ) + 'string'
    print (arr)



































    ReplyDelete
  6. Chetan

    #A ZeroDivisionError is raised when the second argument of a division or modulo operation is zero.
    print (1/0)

    #exception ValueError
    #A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.
    print (int('a'))

    #exception TypeError
    #TypeError is raised when an operation or function is applied to an object of inappropriate type
    arr = ('aditya', ) + 'Chetan'
    print (arr)#can only concatenate tuple (not "str") to tuple

    ReplyDelete
  7. Chetan

    #-exception EOFError

    try:
    n = int(input())
    print(n * 10)

    except EOFError as e:
    print(e)

    ReplyDelete
  8. Chetan

    #-exception KeyError
    #A KeyError is raised when a mapping key is not found in the set of existing keys.
    array = { 'a':1, 'b':2 }
    print (array['c'])
    #because of c (key) is not in the array

    ReplyDelete
  9. Chetan

    #name_error
    def msg():
    try:
    g = "Chetan"
    return ge
    except NameError:
    return "Some variable isn't defined."
    print(msg())

    ReplyDelete
  10. #WAP to validate mobile number using the Exception?
    class ValidateNumber(Exception):
    pass
    try:
    num = int(input("Enter mobile number = "))
    b = str(num)
    c =len(b)
    if c<10 or num == 0000000000 or num == 1234567890:
    raise ValidateNumber
    else:
    print("Your number is " + b)
    except ValueError:
    print("Please Enter Number")
    except ValidateNumber:
    print("Enter Valid Number")




    ReplyDelete
  11. Chetan

    #SystemExit
    #Raised when Python interpreter is quit by using the sys.exit() function.
    #If not handled in the code, causes the interpreter to exit.

    for i in range(10):
    if i == 5:
    try:
    print("hello")
    raise SystemExit
    except BaseException:
    print("It works!")
    finally:
    print(i)
    '''
    try:
    raise SystemExit
    except BaseException:
    print("It works!")

    '''

    ReplyDelete
  12. Chetan
    #syntax Error

    print \\"Message")

    ReplyDelete
  13. #Indentation Error
    try:
    def f():
    z=['foo','bar']
    for i in z:
    if i == 'foo':
    except IndentationError as e:
    print e

    ReplyDelete
  14. #Create a program for addition, subtraction, multiplication, and division using multiple exception block.
    try:
    a = int(input("Ente number = "))
    b = int(input("Enter number = "))

    add = a + b
    sub = a-b
    mul = a*b
    div = a/b

    except ValueError:
    print("Enter Valid Number")

    except ZeroDivisionError:
    print("0 Denominator Not Allowed, Division is not possible")

    except TypeError:
    print("Enter Valid Number")


    else:
    print("No Error")

    finally:
    print("Addition is = ",add)
    print("Substraction is = ",sub)
    print("Multiplication = ",mul)
    print("Division is = ",div)

    ReplyDelete
  15. #Create user-defined exceptions when student fees are>500000 otherwise display fees?
    class StudentFee(Exception):
    pass

    try:
    fee = int(input("Enter Fee = "))

    if fee >50000:
    raise StudentFee
    else:
    print("Fee is = "+str(fee))


    except StudentFee:
    print("Fee should be below 50,000/-")

    except ValueError:
    print("Enter Valid Fee")

    ReplyDelete
  16. try:
    a = int(input("Enter number: "))
    b = int(input("Enter number: "))
    print("Result of Division: " + str(a/b))
    except(ZeroDivisionError):
    print("You have divided a number by zero, which is not allowed.")
    print("Result of Addition: " + str(a+b))
    print("Result of Multiplication: " + str(a*b))
    print("Result of Substraction : " + str(a-b))
    except(ValueError):
    print("You must enter integer value")

    ReplyDelete
  17. i=1
    try:
    f = 3.0*i
    for i in range(100):
    print( i, f)
    f = f ** 2
    except OverflowError as err:
    print ('Overflowed after ', f, err)

    ReplyDelete
  18. 2.
    n = int(input("Please enter a number: "))
    while True:
    try:
    n = input("Please enter an integer: ")
    n = int(n)
    break
    except ValueError:
    print("No valid integer! Please try again ...")
    print("Great, you successfully entered an integer!")

    ReplyDelete
  19. 3.
    try:
    a = int(input("Ente number = "))
    b = int(input("Enter number = "))

    add = a + b
    sub = a-b
    mul = a*b
    div = a/b

    except ValueError:
    print("Enter Valid Number")

    except ZeroDivisionError:
    print("0 Denominator Not Allowed, Division is not possible")

    except TypeError:
    print("Enter Valid Number")


    else:
    print("No Error")

    finally:
    print("Addition is = ",add)
    print("Substraction is = ",sub)
    print("Multiplication = ",mul)
    print("Division is = ",div)

    ReplyDelete
  20. 4.
    class StudentFee(Exception):
    pass

    try:
    fee = int(input("Enter Fee = "))

    if fee >50000:
    raise StudentFee
    else:
    print("Fee is = "+str(fee))


    except StudentFee:
    print("Fee should be below 50,000/-")

    except ValueError:
    print("Enter Valid Fee")

    ReplyDelete
  21. class fee(Exception):
    pass
    try:
    fe=int(input("enter fees of student"))
    if fe<500000:
    raise fee
    else:
    print(fe)
    except fee:
    print("fee should be greater than 500000")

    ReplyDelete
  22. try:
    a=int(input("enter 1st number"))
    b=int(input("enter 2nd number"))
    c=a+b
    d=a-b
    e=a*b
    f=a/b
    print("sum"+str(c)+"substraction"+str(d)+"multiplication"+str(e)+"division"+str(f))
    except ZeroDivisionError:
    print("Please do not enter zero number")
    except ValueError:
    print("please enter correct number")

    ReplyDelete
  23. class mException(Exception):
    pass
    class sException(Exception):
    pass

    try:
    s1=str(input("enter subject"))
    m1=int(input("enter marks"))
    s2=str(input("enter subject"))
    m2=int(input("enter marks"))
    s3=str(input("enter subject"))
    m3=int(input("enter marks"))
    s4=str(input("enter subject"))
    m4=int(input("enter marks"))
    s5=str(input("enter subject"))
    m5=int(input("enter marrks"))
    if m1>100 or m2>100 or m3>100 or m4>100 or m5>100:
    raise mException
    tm=m1+m2+m3+m4+m5
    p=(tm*100)/500
    if p>=75:
    print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with A grade")
    if p>=60:
    print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with B grade")
    if p>=45:
    print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with C grade")
    if p>=33:
    print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with a grade")
    else:
    print("you are fail")


    except mException:
    print("marks should be out of 100")
    except ValueError:
    print("enter right subject name")

    ReplyDelete
  24. class no(Exception):
    pass
    try:
    x=input("enter mobile number")
    c=0
    for i in range(0,len(x)):
    if ord(x[i])>=48 and ord(x[i])<=57:
    c=c+1
    if c<10 or c>10:
    raise no
    except no:
    print("invalid mobile number")
    else:
    print("valid mobile number")

    ReplyDelete
  25. # valid mobile number
    try:
    num=str(input())
    x=list(num)
    c=len(x)

    if c==10:
    if (x[0]=="7" or x[0]=="8" or x[0]=="9"):
    print("valid mobile number",num)
    else:
    print("not valid")
    else:
    print("mobile number should be of ten digit")
    except ValueError as e:
    print(e)
    finally:
    print("please enter valid number")

    ReplyDelete
  26. #WAP to validate mobile number

    try:
    num=str(input("Enter mobile number:"))
    x=list(num)
    c=len(x)

    if c==13:
    if (x[0]=="+91"):
    print("Valid number",num)


    if (x[1]=="7" or x[1]=="8" or x[1]=="9"):
    print("valid mobile number",num)
    else:
    print("not valid")

    else:
    print("Invalid number")

    except ValueError as e:
    print(e)

    ReplyDelete
  27. #Create user-defined exceptions when student fees are>500000 otherwise display fees?

    class FeesException(Exception):
    pass

    try:
    fees=int(input("Enter fees of student:"))
    if fees>500000:
    raise FeesException
    else:
    print("Fees is:"+str(fees))

    except FeesException:
    print("The amount should be less than 500000")

    ReplyDelete
  28. #Addition
    try:
    a=int(input("enter value of a"))
    b=int(input("enter value of b"))
    c=a+b
    print(c)
    except ValueError:
    print("value should be numeric")

    #Subtraction
    try:
    a=int(input("enter value of a"))
    b=int(input("enter value of b"))
    c=a-b
    print(c)
    except ValueError:
    print("value should be numeric")

    #Multiplication
    try:
    a=int(input("enter value of a"))
    b=int(input("enter value of b"))
    c=a*b
    print(c)
    except ValueError:
    print("value should be numeric")

    #Division
    try:
    a=int(input("enter value of a"))
    b=int(input("enter value of b"))
    c=a/b
    print(c)
    except ZeroDivisionError:
    print("denominator should not be zero")
    except ValueError:
    print("value should be numeric")

    ReplyDelete
  29. #Execption on value error and zero division error
    try:
    a=int(input("enter first number"))
    b=int(input("enter second number"))
    c=a/b
    print(c)
    except ValueError:
    print("enter numeric char only")
    except ZeroDivisionError:
    print("demonator can not be zero")

    ReplyDelete
  30. # try.....execpt=finally
    c=0
    res=""
    try:
    a=40
    b=50
    c=a+b
    res="sucess"
    except:
    print("invalid input")
    res="fail"
    finally:
    print("result is",c)
    print("program execution is",res)

    ReplyDelete
  31. 1. Exception
    try:
    a=4
    b="sgg"
    c=a/b
    print(c)
    except Exception:
    print("Default")


    2. Airthmetic error :- Error in numeric calculation

    try:
    a = 10/0
    print (a)
    except ArithmeticError:
    print ("This statement is raising an arithmetic exception.")
    else:
    print ("Success.")


    3. OverFlowError - When calculation is exceeded to maximum limit
    try:
    import math
    print(math.exp(10))
    except OverflowError:
    print("Error")


    4. FloatingPointError : Failure in floating calculation
    try:
    a=1.3
    b=1.1
    c=a-b
    print(c)

    except FloatingPointError:
    print("Error")


    5. ZeroDivisionError: - Denominator should not be 0.
    try:
    a=10
    b=0
    c=a/b
    print(c)
    except ZeroDivisionError:
    print("error")


    6. AssertionError: - Failure of assertion statement
    try:
    x = 1
    y = 3
    assert y != 3, "Invalid Operation"
    print(x / y)

    except AssertionError:
    print("Error")


    7. AttributeError:- failure of attribute reference or assignment.
    try:
    class fg:
    def __init__(self):
    self.a ="byh"
    obj = fg()
    print(obj.a)
    print(obj.b)

    except AttributeError:
    print("Error")

    8. NameError: - when an identifier is not found in the local or global namespace.
    try:
    class fg:
    def __init__(self):
    self.a ="byh"
    obj = java()
    print(obj.a)


    except AttributeError:
    print("Error")




    ReplyDelete
  32. try:
    #Addition
    a=int(input("enter number: "))
    b=int(input("enter number: "))
    c=a+b
    print(c)
    except ValueError:
    print("value should be numeric")
    print()
    #Multiplication
    try:

    a=int(input("enter number: ")) #raise addException
    b=int(input("enter number: "))
    c=a*b
    print(c)
    except ValueError:
    print("number should be numberic")
    #Dvivision
    a=int(input("enter number: "))
    b=int(input("enter number: "))
    s=a/b
    print(s)

    except ValueError:
    print("denominator can not be zero")
    print()
    try:
    a=int(input("enter number"))
    b=int(input("enter number"))
    c=a-b
    print(c)
    except ValueError:
    print("value should be numeric")

    ReplyDelete
  33. # program of addition using multiple exception block.
    # Anjali verma
    try:
    a=int(input("enter first number"))
    b=int(input("enter second number"))
    c=a+b
    print(c)
    except ValueError:
    print("enter only numeric value")

    ReplyDelete
  34. # program of subtraction using multiple exception block.
    # Anjali verma
    try:
    a=int(input("enter first number"))
    b=int(input("enter second number"))
    c=a-b
    print(c)
    except ValueError:
    print("enter only numeric value")

    ReplyDelete
  35. # program of multiplication using multiple exception block.
    # Anjali verma
    try:
    a=int(input("enter first number"))
    b=int(input("enter second number"))
    c=a*b
    print(c)
    except ValueError:
    print("enter only numeric value")

    ReplyDelete
  36. # program of division using multiple exception block.
    # Anjali verma
    try:
    a=int(input("enter first number"))
    b=int(input("enter second number"))
    c=a/b
    print(c)
    except ValueError:
    print("denominator should not be zero")

    ReplyDelete
  37. #valid gmail

    class emailException(Exception):
    pass
    try:
    email = input("enter email: ")
    atpos = 0
    dotpos = 0
    i = 0
    c = 0
    for e in email:
    if e==".":
    dotpos=i
    elif e=="@":
    atpos=i
    c=c+1
    i=i+1
    if atpos==0 or dotpos==0 or atpos>dotpos or c>1 or dotpos-atpos<2 or dotpos==len(email):
    raise emailException
    print("valid email",email)
    except emailException:
    print("invalid email",email)

    ReplyDelete
  38. try:
    a = int(input("Enter First Number "))
    b = int(input("Enter Second Number "))
    c = a/b
    print(c)
    except ZeroDivisionError:
    print("denominator can not be zero")

    ReplyDelete
  39. # To validate email id
    class error(Exception):
    pass
    try:
    a=input("enter email id:-")
    b=a.count("@")
    if b==0:
    raise error("@ not present")
    elif b==2:
    raise error("only 1 @ is allowed but 2 given")
    else:
    d=a[a.find("@"):]
    if d.count(".")>0:
    if d.index(".")-d.index("@")>=6:
    if len(d)-d.index(".")>=2:
    raise error("Valid email id")
    else:
    raise error("after dot atleast 1 words should present")
    else:
    raise error("Required distance bewteen @ and . is less it should be atleast 5")
    else:
    raise error("ATLEAST DOT SHOULD PRESENT")
    except error as e:
    print(e)

    ReplyDelete
  40. #CHECK VALID MOBILE NUMBER
    class error(Exception):
    pass
    try:
    a=input("enter mobile number:-")
    if a.isnumeric()==False:
    raise error("Alphabet not allowed")
    else:
    if len(a)==10:
    print("Valid mobile number")
    else:
    raise error("Mobile number should consist 10 digit")
    except Exception as e:
    print(e)

    ReplyDelete
  41. Pawan Singh Rathore
    Batch Python (11AM to 12PM)

    class ValidMobileNumber(Exception):
    pass
    try:
    a=input("enter mobile number:-")
    if ((a >= 'a' and a <= 'z') or (a >= 'A' and a <= 'Z')):
    raise ValidMobileNumber
    elif len(a)==10:
    print("Valid mobile number")
    else:
    raise ValidMobileNumber
    except ValidMobileNumber:
    print("Number should be 10 digit or Alphabet character not allowed")



    ReplyDelete
  42. Manage mark sheet program with all possible exception


    class mraskException(Exception):
    pass
    class subjectException(Exception):
    pass

    try:
    sub1=str(input("enter subject"))
    mrask1=int(input("enter marks"))
    sub2=str(input("enter subject"))
    mrask2=int(input("enter marks"))
    sub3=str(input("enter subject"))
    mrask3=int(input("enter marks"))
    sub4=str(input("enter subject"))
    mrask4=int(input("enter marks"))
    sub5=str(input("enter subject"))
    mrask5=int(input("enter marrks"))
    if mrask1>100 or mrask2>100 or mrask3>100 or mrask4>100 or mrask5>100:
    raise mraskException()
    tm=mrask1+mrask2+mrask3+mrask4+mrask5
    p=(tm*100)/500
    if p>=75:
    print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with A grade")
    elif p>=60 and p<=75:
    print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with B grade")
    elif p>=45 and p<=60:
    print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with c grade")
    elif p>=33 and p<=45:
    print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with D grade")
    elif p<=32:
    print("your percent is"+str(p)+"your total marsk"+str(tm)+"you are fail")

    except mraskException():
    print("marks should be out of 100")
    except ValueError:
    print("enter your only number for marsk")

    ReplyDelete
  43. WAP to validate mobile number using the Exception?

    class no(Exception):
    pass
    try:
    x=input("enter mobile number")
    c=0
    for i in range(0,len(x)):
    if ord(x[i])>=48 and ord(x[i])<=57:
    c=c+1
    if c<10 or c>10:
    raise no
    except no:
    print("invalid mobile number")
    else:
    print("valid mobile number")

    ReplyDelete
  44. try:
    first=int(input("enter a first number"))
    second=int(input("enter a second number"))
    operator=input("enter a operator")
    if operator=="+":
    print(first + second)
    if operator=="-":
    print(first - second)
    if operator=="*":
    print(first * second)
    if operator=="/":
    print(first / second)
    if operator=="%":
    print(first % second)
    except ZeroDivisionError:
    print("Denominator Can't Be Zero")
    except ValueError:
    print("Print Only Numeric Value")

    ReplyDelete
Post a Comment