× Python Introduction What is Python Python Features Python History Python Applications Python Install Python Path Python Example Execute Python Keywords Constant Variable Statements & Comments Python I/O and Import Operators UnaryBinaryTernary Unary Operators Unary Minus Binary Operators Arithmetic Operators Assignment Operators Relational Operators Logicaloperators Bitwise Operator Ternary Operators Control Statements in Python conditonal Statements IF if else Else If Nested if Switch For loop Nested For Loop While Loop Nested while Loop Unconditonal Statemets Continue Break Pass FUNCTIONS Python Function Function Argument Python Recursion Anonymous Function Python Modules NATIVE DATATYPES Python List Python Numbers Python Tuple Python String Python Set Python Dictionary OOPS PRINCIPALS Encapsulation Class Variable Method Object Or Instance CreationMethod Calling OOPS Syntax And Explanation DATA ABSTRACTION Constructor Inheritance 1.Single or simple Inheritance 2.Multilevel Inheritance 3.Hierarchical Inheritance 4.Multiple Inheritance 5.Hybrid Inheritance Operator Overloading File Operation Python Directory Python Exception Python - Multithreading Python - Database Access Python - CGI Python - Reg Exp Python - Date Python - XML Processing Python - GUI
  • iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

Exception Handling


Error

Error is an abnormal condition whenever it occurs execution of the program will be stopped. In Python language errors are classified into two types.
1.Compile time errors
2.Runtime errors

Compile time errors:
These are the errors generated at compile time because of breakdown the rules of a programming language.
Example:
Missing semicolon at the ending of a statement.
Writing keywords in upper case etc..
Note:
Compile time errors are also known as syntax errors.

Runtime errors:
These are the errors generated at the time of running of a program and these are raised because of writing wrong logic or because of providing wrong input values. Runtime errors are also known as Exceptions.
Example:
valueError
TypeError

In the real time application development it is very necessary to identify either runtime exception or compile time error to get efficient output.
Compile time errors can be identified and solved by the developers, but runtime errors may be generated or raised to the end user at the time of running of an application. .
Whenever runtime error is generated python raises system defined error message, that may not understandable by the en user so that as a Python developer this is our responsibility to convert system define error message to user friendly error message for better understanding or identification purpose ,in Python language it can be possible using exception handling.
Definition of Exception Handling:

Exception handling is a special mechanism used to convert system defined error messages onto user friendly error messages. In Python language exception handling can be achieved using try-except construction.

Image
Try-except Construction:

In Python language exception handling can be achieved using try-except block construction.
Try and except blocks are the keywords in the Python language, it is used to convert System Defined Error Messages into User Friendly Error Messages very efficiently. Try block always contains logic of the program or problematic code, except block contains User Friendly Error Messages. Syntax:

Try:
	Logic of the code
Except NameOfTheExcepton1  as object:
	User Friendly Message
Except NameOfTheExcepton2  as object:
	User Friendly Message
Except NameOfTheExcepton3  as object:
	User Friendly Message

    


Rules To Create A try-except Block
1.One try block can have many number of Exception Statements , but it raises only One Exception at a time.
2.One except block can handle only One Exception at a time.
3.For one try block multiple except blocks are exists.
4.Without try block no except block can exist.
5.Without except block try block can exist if it is containing finally block otherwise it is not possible.
6.The statements of try block are executed whenever program is executed but the statements of except block are executed whenever exception is raised.
7.Once control comes out of the try block control will never return back to same block to execute the statements.


A Python program can contain multiple try –except block to handle multiple Exceptions at a time.
    
Try:
	Logic of the code
Except NameOfTheExcepton1  as object:
	User Friendly Message
 
Try:
	Logic of the code
Except NameOfTheExcepton1  as object:
	User Friendly Message
 



Nested try-except
if any try-except block is existing another try or except block is known as nested try-except .this is an alternative approach to handle multiple exceptions at a time .but this is not recommended in real time applications because it is irreliableor insufficient handling if exception.
Try:
    Try:
        Logic of the code
    Except NameOfTheExcepton1  as object:
        User Friendly Message
Except NameOfTheExcepton1  as object:
    try:
        Logic of the code
    Except NameOfTheExcepton1  as object:
        User Friendly Message

Exception Handling

Image
Write a program to handle try with single except block
Write a program to handled the Arithmetic Exception
def myfun():
    try:
        x=int(input("Enter x value"))
        y=int(input("Enter y value"))
        z=x/y
        print("Division Of Two Number Is ",z)
 
    except ZeroDivisionError as z:
        print("Denominator should not be zero")



if __name__=="__main__":
    myfun()



                                

Output:
Enter x,y values
10
2
Division Of Two Number Is 5


Enter x,y values
10
0
Denominator should not be zero
Write a program to handle try with Multiple except blocks
Write a program to handled the Arithmetic Exception
def myfun():
    try:
        x=int(input("Enter x value"))
        y=int(input("Enter y value"))
        z=x/y
        print("Division Of Two Number Is ",z)
    except ValueError as p:
        print("pls enter numbers only")

    except ZeroDivisionError as z:
        print("Denominator should not be zero")



if __name__=="__main__":
    myfun()



                                

Output:
Enter x,y values
10
2
Division Of Two Number Is 5


Enter x,y values
10
0
Denominator should not be zero

Finally block:
It is a keyword in python language ,it is collection of statements existed in the form of block finally block.
Finally block contains the statements of try block which are existing mandatary irrespective raising exception (Either exception is raised or not raised). Syntax:
finally:
    ...
    ...
    ...
    
                                      
 def myfun():
    try:
        x=int(input("Enter x value"))
        y=int(input("Enter y value"))
        z=x/y
        print("Division Of Two Number Is ",z)
        #print("Hi"); 
    except ValueError as p:
        print("pls enter numbers only")

    except ZeroDivisionError as z:
        print("Denominator should not be zero")
    finally:
        print("Hi"); #try block statement
    



if __name__=="__main__":
    myfun()

User defined Exception:

If any exception is designed by the user and it if used commonly by specific number of developers is known as user defined exception.
If any exception is unable to handle by the Python then those type of exceptions can be handled by the user by creating separate execution block.

Rules to design user defined exception:

1.Create a class and inherit Exception
2.call the exception class Using raise keyword
3.handle the user defined Exception using except block
Syntax:

Class classname(Exception):
	Pass:
 
Def show():
	Try:
	    if(condition):
			Raise classname
	Except classname:
		 	User Friendly Message    


class err(Exception):
    pass

def myfun():
    try:
        x=int(input("Enter x value"))
        y=int(input("Enter y value"))
        if(x<0 or y<0 or x>1000 or y>1000):
            raise err
        z=x/y
        print(z)
    except ValueError as v:
        print("Pls enter numbers only")
    except ZeroDivisionError as z:
        print("Denominator should not be zero")
    except err as e:
        print(" pls enter valid numbers")
    

if __name__=="__main__":
    myfun()




                                

User defined Exception Program-2


class A(Exception):
    pass
 
class nerr(A):
    pass
 
class berr(A):
    pass
 
def myfun():
    try:
        x=int(input("Enter x value"))
        y=int(input("Enter y value"))
        if(x<0 or y<0):
            raise nerr
        elif x>1000 or y>1000:
            raise berr
        else:
            z=x/y
            print(z)
    except ValueError as p:
        print("pls enter numbers only")
 
    except ZeroDivisionError as z:
        print("Denominator should not be zero")
 
    except nerr as n:
        print("pls enterpositive numbers")
    except berr as b:
        print("Pls enter below 1000 number")
    
 
 
if __name__=="__main__":
    myfun()