Pages

Friday, September 29, 2017

Python Try and Except

try:
pass
except Exception:
pass
else:
pass
finally:
pass

f = open('_comment.py')
try:
        pass
except Exception:
        pass

try:
f = open('_comment.py')
except Exception: ## whatever is the error everytime it will print below message.
print('Sorry. the file does not exist')

try:
        f = open('comment.py')
        var = bad_var
except Exception: ## let's provide correct file name. This too will print below error message
        print('Sorry. the file does not exist')

## instead of exception we can say file not found error

## this will only print name error
try:
        f = open('comment.py')
        var = bad_var
except FileNotFoundError:
        print('Sorry. the file does not exist')

try:
        f = open('comment.py')
        var = bad_var
except FileNotFoundError:
        print('Sorry. the file does not exist')
except Exception:
print('Sorry. Something went wrong')

## instead of printing custom message let's print exception
try:
        f = open('comment.py')
        var = bad_var
except FileNotFoundError as e:
        print(e)
except Exception as e:
        print(e)

# lets remove bad_var. it runs without any error

try:
        f = open('comment.py')
except FileNotFoundError as e:
        print(e)
except Exception as e:
        print(e)

try:
        f = open('_comment.py')
except FileNotFoundError as e:
        print(e)
except Exception as e:
        print(e)

## if try doesn't run any exception, else section will execute. This will read file
try:
        f = open('comment.py')
except FileNotFoundError as e:
        print(e)
except Exception as e:
        print(e)
else:
print(f.read())
f.close()
## code under else can be placed under try statement as well but it wise not to do that

## finally runs whether code is successful or not. This execute else as well as finally section
try:
        f = open('comment.py')
except FileNotFoundError as e:
        print(e)
except Exception as e:
        print(e)
else:
        print(f.read())
        f.close()
finally:
print("Executing finally")

## let's place wrong file. this will catch exception and execute finally section
try:
        f = open('_comment.py')
except FileNotFoundError as e:
        print(e)
except Exception as e:
        print(e)
else:
        print(f.read())
        f.close()
finally:
        print("Executing finally")

## we can raise exception on our own ie manually
try:
        f = open('apr-24.txt')
        if f.name == 'apr-24.txt':
raise Exception
except FileNotFoundError as e:
        print(e)
except Exception as e:
        print('Error!')
else:
        print(f.read())
        f.close()
finally:
        print("Executing finally")






No comments:

Post a Comment