Python Try Except Statement
Python Try Except statement can help us to handle possible errors within our code, below we will explain its component and also how to use this Try Except Python statement in your code. Let’s try to understand how to use this Python statement and why is this so important in our day to day Python coding.
Statement components
The first block called try
lets you test a block of code for any errors that may appear in your code.
Second block called except
will handle basically the error that may exist.
The third block named finally
it is optional and lets you execute code, regardless of the result of the try and except blocks.
Examples
The try
block in the example below will generate an exception, because in this particular case as you can see x
is not defined at all:
try:
print(x)
except:
print("An exception occurred")
Shortly we will add more examples.