xxxxxxxxxx
# Try & Except :-
# Try => Test The Code For Errors
# Except => Handle The Errors
# The Try & Except ==> Complete Each Other
# You Can't Type One Without The Other
# Example, We Need From The User To Write His Age
# Age Mean Integer
# But What If He Type String
# Of Course We Show To Him Wrong Message
try : # I Will Try The Code
# If The User Type His Age, Mean Integer
age = int( input( "Write Your Age Please: " ) )
# This Message Will Show To Him
print( f"Your Age Is {age}" )
except : # If I Found Error, I Will Show To Him Wrong Message
# But If He Type Something Else, This Message Will Show To Him
print( "Wrong Value, Please Try Again" )
xxxxxxxxxx
try:
# Dangerous stuff
except ValueError:
# If you use try, at least 1 except block is mandatory!
# Handle it somehow / ignore
except (BadThingError, HorrbileThingError) as e:
# Hande it differently
except:
# This will catch every exception.
else:
# Else block is not mandatory.
# Dangerous stuff ended with no exception
finally:
# Finally block is not mandatory.
# This will ALWAYS happen after the above blocks.
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:
#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
try:
Age = int(input("Your Age:- "))
except ValueError:
print("Age not in Intger form")