Pacific-Design.com

    
Home Index

1. Python

2. Exception

Python / Exception /

Python - Exception

#!/usr/bin/python3

def main():

    try:
        fh = open('doesnotexist.txt')
    except:
        print('Trying to open something does not exist')
    else:
        for line in fh: print(line.strip())

if __name__ == "__main__": main()


Python - Specific Exception

#!/usr/bin/python3

def main():

    try:
        fh = open('doesnotexist.txt')
    except IOError as e:
        print('Could not open the file:', e)
    else:
        for line in fh: print(line.strip())

if __name__ == "__main__": main()

Python - Raise and Catch Exception

#!/usr/bin/python3
# Bad filename extension Filename must end with .txt
def main():

    try:
        for line in readfile('file.dat'): 
            print(line.strip()) 
    except IOError as e:
        print('Could not open the file:', e)
    except ValueError as e:
        print('Bad filename extension', e)

def readfile(filename):
    if filename.endswith('.txt'):
        fh = open(filename)
        return fh.readline()
    else: raise ValueError('Filename must end with .txt')


if __name__ == "__main__": main()