xxxxxxxxxx
try:
#some code that may will produce an error
except:
#some code that will be executed if an error is encountered
finally:
#this code always will be executed
xxxxxxxxxx
try:
print("I will try to print this line of code")
except:
print("I will print this line of code if an error is encountered")
xxxxxxxxxx
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
xxxxxxxxxx
try:
print("I will try to print this line of code")
except ERROR_NAME:
print(f"I will print this line of code if error {ERROR_NAME} is encountered")
xxxxxxxxxx
try:
val = 1/0
except Exception as e:
raise Exception('ZeroDivisionError')
xxxxxxxxxx
try:
# tests code that may cause errors
except Exception as e:
# handles the error
else:
# executed when there is no error
finally:
# always executed
xxxxxxxxxx
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
xxxxxxxxxx
try:
Age = int(input("Your Age:- "))
except ValueError:
print("Age not in Intger form")
xxxxxxxxxx
'''
In python, you can use try, except and finally to catch errors to keep
running your code even when you run into an error.
try:
# insert code
except SpecificError:
# code that will run if the code in 'try' doesn't work
finally:
# always runs this code, error or not
'''
try:
myVar = 10 / 0 # runs into an error
except ZeroDivisionError as error:
print(error) # prints error to user
finally:
print('Finished try, except, finally') # always prints
xxxxxxxxxx
'''
We can use try and except to continue running code even if we
come across an error.
'''
try:
var = 0 / 0 # Runs into error
except ZeroDivisionError as e:
print(e) # Prints the error
# ADD ANY OTHER CODE YOU WANT TO EXECUTE