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

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes