Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

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))






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?












.



5 Comments

If you have any doubt in programming or join online classes then you can contact us by comment .

  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

Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post