Python Try Except :

Python Try Except :

The try block lets you test a block of code for errors. The except block lets you handle the error. The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling :

When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using the try statement:

Example :

  1. #The try block will generate an exception, because x is not defined
  2. try:
  3. print(x)
  4. except:
  5. print("An exception occurred")
  6. input()

Output :

python try except example

Many Exceptions :

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error. So, print one message if the try block raises a NameError and another for other errors :

  1. try:
  2. print(x)
  3. except NameError:
  4. print("Variable x is not defined")
  5. except:
  6. print("Something else went wrong")
  7. input()

Output :

python many try except example

Finally :

The finally block, if specified, will be executed regardless if the try block raises an error or not.

Example :

  1. try:
  2. print(x)
  3. except:
  4. print("Something went wrong")
  5. finally:
  6. print("The 'try except' is finished")
  7. input()

Output :

python finally try except example

Next Update

Loading...

Currently we improved our website User Interface and other contents. Our next update is adding video tutorials on this site so, We create a new YouTube channel, our YouTube channel name is CodeX.

We need some time for make video tutorials (CodeX) so, stay with us and keep supporting and you know already we make a Collaboration with HackIsOn YouTube channel long time ago So, please Subscribe Our Channels