Python try except | Finally | Else | Print Error Examples

Python try except block are used for exception handling or error handling. With the use of try-except block in your program, you can allow your program to continue or terminate at a point or show messages.

If an error occurred in the program, then try block will pass to except block. In addition, you can also use a finally block to execute whether an exception occurs or not.

Python try except | Finally | Else | Print Error Examples ne

Important terms in Python try except block.

  • try a block of code to the probability of error.
  • except block lets you handle the error.
  • else block if no exception in the program.
  • finally regardless of the result of the try- and except blocks, this code always executes.

Syntax :

Simple syntax of try except block.

Python try except Example 

This is a simple sample of try-except block in python. If the arithmetic operation will be done then nothing print otherwise the output will be an error message.

Output: An exception occurred

Example try except a print error in python

An example of how to python “except exception as e” and print error in console.

Output: division by zero

Example try except Else

You can use python try except else to execute a block of code in if no error raised.

Output: 1.0
No Error

Example try except Finally in Python

Finally, code of block always execute on error or not.

Output: division by zero
Always print finally python code

QA: What is the use of finally block in Python try except error handling?

It can be an interview question.

Finally, the block can be useful to close objects and clean up resources, like close a writable file or database.

Like this example of writing a file in python.

case: if file existing or creates it.

Output: File Closed

case: if file not existing

Python try except Finally output


Note: This tutorial is explained about exception handling blocks and how to use it. You must read about details about exception handling in this tutorial – Python exception Handling | Error Handling

As another language like Java using a try catch for exception handling. If you are looking for a python try-catch, then you will not find it. Python has a try-except instead of try-catch exception handling.

Do comment if you have any doubts and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All examples are in try except python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.