Python Tutorials
Python File Handling
Python Modules
Try
block lets you check the code block for errors.
The except
block lets you manage an error.
The block finally
allows you to create code, regardless of the result of trying and without blocks.
In the event of an error, or otherwise as we call it, Python will usually stop and produce an error message.
These exceptions can be addressed using the try
statement:
The try
block will generate an exception, because x
is not defined:
try:
print(x)
except:
print("An exception occurred")
As the try block suggests an error, the except block will be used.
Without a try block, the system will crash and crash:
This statement will raise an error, because x
is not defined:
print(x)
You can define as many different blocks as you want, e.g. if you want to create a special block code for a special type of error:
Print one message if the try block raises a NameError
and another for other errors:
try:
print(x)
except NameError:
print("Variable x
is not defined")
except:
print("Something else went
wrong")
You can use else
keyword to define a code block to use when no errors are suggested:
In this example, the try
block does not generate any error:
try:
print("Hello")
except:
print("Something went
wrong")
else:
print("Nothing went wrong")
The finally
block in the, if specified, will be used whether the try block suggests an error or not.
try:
print(x)
except:
print("Something went
wrong")
finally:
print("The 'try except' is finished")
This can be useful for shutting down and cleaning utilities:
Try to open and write to a file that is not writable:
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")
The program can continue, without leaving the file object open.
As a Python engineer you can choose a different throw in case.
To throw (or suggest) something different, use the raise
keyword.
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below
zero")
The keyword raise
is used for a different suggestion.
You can specify what type of error should be raised, as well as the text to be printed on the user.
Raise an error and stop the program if x is lower than 0:
x = "hello"
if not type(x) is int:
raise TypeError("Only
integers are allowed")