All technological notes.
try block: test a block of code for errors.except block: handle the error.else block: execute code when there is no error.finally block: execute code, regardless of the result of the try and except blocks.When an error (or called as exception) occurs, Python will normally stop and generate an error message.
Since the try block raises an error, the except block will be executed.
try block, the program will crash and raise an error.define exception blocks
try:
print(x) # x is not defined
except NameError:
print("Variable x is not defined") # execute
except:
print("An exception occurred")
Else
define a block of code to be executed if no errors were raised
print("\n--------else--------\n")
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong") # executed
Finally
finally block, if specified, will be executed regardless if the try block raises an error or not.print("\n--------finally--------\n")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished") # executed
print("\n--------finally: close file--------\n")
try:
f = open("./demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
raise to throw (or raise) an exceptionprint("\n--------raise--------\n")
x = -1
try:
if x < 0:
raise Exception("Sorry, no numbers below zero")
except Exception as ex:
print(ex) # Sorry, no numbers below zero
x = "hello"
try:
if not type(x) is int:
raise TypeError("Only integers are allowed")
except TypeError as ex:
print("TypeError: {ex}".format(ex=ex)) # TypeError: Only integers are allowed
except Exception as ex:
print("Exception: {ex}".format(ex=ex))
class CustomizedException(Exception):
print("inside")
pass
try:
raise CustomizedException()
except CustomizedException:
print("Raised customized exception.")
# inside
# Raised customized exception.
print("\n--------Example: with statement--------\n")
print("\n--------try except")
filename = "test.txt"
try:
file = open(filename, 'r')
try:
content = file.read()
print(content)
except Exception as err:
print(err)
finally:
file.close()
except FileNotFoundError as err:
print(err)
else:
print("success")
print("\n--------with statement")
try:
with open(filename, 'r') as file:
content = file.read()
print(content)
except Exception as err:
print(err)
else:
print("success")