Python Exception

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:


The try block will generate an exception, because x is not defined:

  print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:


This statement will raise an error, because x is not defined:


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:


Print one message if the try block raises a NameError and another for other errors:

except NameError:
  print("Variable x 
  is not defined")
  print("Something else went 


You can use the else keyword to define a block of code to be executed if no errors were raised:


In this example, the try block does not generate any error:

Python Try Except

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.Note: For more information, refer Errors and Exceptions in PythonSome of the common Exception Errors are :  


Try Except in Python

Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block. 


    # Some Code
    # Executed if error in the
    # try block

How try() works?  

Code 1: No exception, so try clause will run.  

Output :  

 ('Yeah ! Your answer is :', 1)

Code 1: There is an exception so only except clause will run.  

Output :  

 Sorry ! You are dividing by zero


In python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception. 

For more, checkout W3Schools and Geeks For Geeks.