Monday, 29 July 2024

Python Unit - IV

 

Python Topics

1.      Exception Handling

a.      Errors and Types of Errors

b.      Exception Handling & Types

c.       Multiple Exception

d.      User defined Exception

2.      Python File Handling


 

1. Exception Handling

Error: Some mistake

Types of Error

------------------

1. compile time error

2. Runtime error

1. Compile Time Error

§  A compile time error refers to the error that we encounter during the code compilation

   Ex: Statement missing, declaration error, syntax error

 

2. Run Time Error

§  A runtime error refers to the error that we encounter during the code execution at runtime

   Ex: Source error, File missing error, Arithmetic error, Number format error, Array Index error

Drawback: System going to Abnormal condition, to avoid this situation using Exception

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Syntax:

---------

try: 

   statement 

except Exception1: 

    execute code 

.... 

except ExceptionN: 

    execute code 

else: 

    In case of no exception, execute the else block code.

 

1) Try:

 -------

->A function using an exception should be in a "try" block.

->If the exception does not trigger, the code will continue as normal. ->However if the exception triggers, an exception is "thrown"

2) Throw:

-----------

->This is how you trigger an exception.

->Each "throw" must have at least one "catch"

3) Catch:

----------

-> A "catch" block retrieves an exception and creates an object containing the exception information

4) Finally:

-----------

->finally block may also be specified after the catch blocks. ->Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 Types of Exception

-------------------

1. ZeroDivisionError: Occurs when a number is divided by zero.

2. NameError: It occurs when a name is not found. It may be local or global.

3. IndentationError: If incorrect indentation is given.

4. IOError: It occurs when Input Output operation fails.

5. EOFError: It occurs when end of file is reached and yet operations are being performed

6. ArithError

7. ValueError

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1. What is an Exception?

An exception is an error that happens during execution of a program. When that error occurs, Python generate an exception that can be handled, which avoids your program to crash.

2. Why use Exception?

Exceptions are convenient in many ways for handling errors and special conditions in a program. When you think that you have a code which can produce an error then you can use exception handling.

#Program 1: using Exception

try:

    a=int(input("Enter First input : "))

    print("Output is :",a)

except ValueError:

    print("Input Error")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: using Multiple Exception

try:

    a=int(input("Enter First input : "))

    b=int(input("Enter second input : "))

    c=a/b

    print("Output is :",c)

except ZeroDivisionError:

    print("cant Divide zero Error")   

except ArithmeticError:

    print("Arithmetic Error")

except ValueError:

    print("Input Format Error")

finally:

    print("End of Program")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3: Program for multiple try block

try:

    a=float(input("Enter First input : "))

    b=float(input("Enter Second input: "))

    c=(float)(a)/b

    print ("Division is",c)

except Exception as e:

    print ("Input Error",e)

try:

    a=int(input("Enter First input : "))

    b=int(input("Enter Second input: "))

    c=a+b

    print ("Addition is",c)

except Exception as e:

    print ("Input Error",e)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4: used Defined Exception

try: 

    a=int(input("enter the value of a :"))

    if a<0: 

     raise NameError("-ve not allowed")

    else:

        print(a)

except NameError as e: 

        print ("An exception occurred",e) 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


 

2. Python File Handling

Python Files:

------------------

§  File is a collection of related Data Items (Information).

§  This Data Items stored on secondary Memory space (hard disk)

§  Python has several functions for creating, reading, updating, and deleting files.

File Operations

--------------------

1. Opening a File

Syntax:       obj=open(filename , mode , buffer)

2. Closing a file

Syntax:        fileobject.close()

3. Writing to a file

Syntax:

         fileobject.write(string str)

4. Reading from a File

Syntax:

      fileobject.read(value) 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Opening, Writing & Closing a file

f1=open("test1.txt",'w')

f1.write("welcome to python")

f1.write("\nhello world")

print ("Successfully created..!")

f1.close()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Opening, Reading & Closing a file

f1=open("test1.txt",'r')

print(f1.read())

f1.close()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3: Renaming a File

import os

os.rename("test1.txt","test2.txt")

print("Successfully Renamed")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4: Removing a File

import os

os.remove("test2.txt")

print("Successfully Removed")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 5: Make Directory or Folder

import os

os.mkdir("jahab")

print("Successfully Create a Folder")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6: Remove Directory or Folder

import os

os.rmdir("jahab")

print("Successfully Remove Folder")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

No comments:

Post a Comment