Python Tutorial

Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Monday, February 18, 2013

Python exceptions



All source code available on github

try:
    v = 1/0
except ZeroDivisionError:
    print "Divide by zero"

try:
    v = "CSE"
    int(v)
except ValueError:
    print "Value error"

try:
    raise Exception("Exception info")
except Exception as data:
    print data.args


Output:
Divide by zero
Value error
('Exception info',)

File read code snippet



All source code available on github

import sys

def readFile(filename):
    try:
        file = open(filename,'r')
        content = file.read()
        file.close()
        return content
    except IOError:
        print "IOError:",IOError.args[0]
    except :
        print "Unexpected error:",sys.exc_info()[0]
        raise

Friday, August 20, 2010

python exception handling

'''
   This code use exception handling syntax
'''

directory ="C:/pythonInputFile.txt"
try:
    f=open(directory,'r')
    print f.read()
    f.close()
except:
    print "File not found/problem on reading file"
finally:
    print "It always works"

python rename a file

'''
   This code use for rename a file
      - also change the file format
      - example of exception handling
'''
import os
import sys

currentDirectory="C:/pythonFile.txt"
if os.path.exists(fileDirectory):
    try:
        newFileName="pythonInputFile.doc"
        newDirectory=fileDirectory[0:fileDirectory.rfind("/")+1]+newFileName
        print newDirectory
        os.rename(currentDirectory,newDirectory)
    except:
        print "Exception: ",str(sys.exc_info())
else:
    print "File Not found"





Output:
Check current directory folder