Python Exception Handling

Python can handle exceptions (Exceptions are error, that are not the normal execution of a program).

Taking care of exceptions is called Exception Handling. Python does that with the try, except and finally blocks.

  • try block has code that may raise exceptions
  • except block handles exceptions
  • finally block code is always executed

Related course: Complete Python Programming Course & Exercises

How to Handle Exceptions in Python?

try, except, finally is an exception-catching mechanism in Python, which is usually used in combination with try...except.

If an exception is found, it will be passed to a block in the except for processing, that is, to execute the statements in the except. The syntax to handle exceptions is:


Of course, try...except can also be used in conjunction with finally.

The content of the finally block is run only in the end, but usually does something simple like release a resourceor something.

The finally block is always executed, even if there is an Exception in the previous try and except blocks.

try-except Blocks Example

Here's a simple example of exception handling with a try except block.


def tryTest():  
        den = input("input a number:")  
        x = 1.0/int(den)  
        return 1  
        return 0  
        print("this is a finally test")

result = tryTest()  


When the input is 1, the program does not catch the exception, then the return value is 1, but before the return will execute the finally statement block, that is, print the sentence "this is a finally test", as follows.

python try except

When the input is 0, the program does not catch the divide 0 exception and executes the statement block in except, then the return value is 0, but the statement block in finally is executed before the return, as shown below.

python exception handling

So anyway the code in the finally statement block is executed, if there is a return statement in the finally, then the whole function will return from the return statement in the finally, the previous return statement is useless.