added else statement with try except
also added some more explanation
This commit is contained in:
@@ -1,3 +1,20 @@
|
|||||||
|
# something more about try except
|
||||||
|
# basic syntax
|
||||||
|
'''
|
||||||
|
try:
|
||||||
|
code1
|
||||||
|
|
||||||
|
except:
|
||||||
|
some code that will execute if code 1 fails or raise some error
|
||||||
|
|
||||||
|
else:
|
||||||
|
this code is executed only if try was succesful i.e no error in code1
|
||||||
|
|
||||||
|
finally:
|
||||||
|
|
||||||
|
this code will execute in every situation if try fails or not
|
||||||
|
'''
|
||||||
|
|
||||||
filename = 'exception_data.txt'
|
filename = 'exception_data.txt'
|
||||||
# Outer try block catches file name or file doesn't exist errors.
|
# Outer try block catches file name or file doesn't exist errors.
|
||||||
try:
|
try:
|
||||||
@@ -28,4 +45,22 @@ def this_fails():
|
|||||||
try:
|
try:
|
||||||
this_fails()
|
this_fails()
|
||||||
except ZeroDivisionError as err:
|
except ZeroDivisionError as err:
|
||||||
print('Handling run-time error:', err)
|
print('Handling run-time error:', err)
|
||||||
|
|
||||||
|
|
||||||
|
def divide_me(n):
|
||||||
|
x = 1/n
|
||||||
|
|
||||||
|
i = int(input('enter a number '))
|
||||||
|
try:
|
||||||
|
divide_me(i)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(e) # this will print the error msg but don't kill the execution of program
|
||||||
|
|
||||||
|
else:
|
||||||
|
print('Your Code Run Successfully') # this will execute if divide_me(i) run sucessfully without an error
|
||||||
|
|
||||||
|
finally:
|
||||||
|
print('thanks') # this will execute in every condition
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user