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.

Video

No video posted for this page.

Screenshots

No screenshots posted for this page.

Source code

No code posted for this page.

About this page

Article
Python Try Except Statement
Author
Category
Published
12/11/2018
Updated
12/11/2018
Tags

Share this page

If you found this page useful please share it with your friends or colleagues.