Python Basics

Python Try Except Else Finally: Beginner python tutorials 21 | Better4Code

Know about Python Try Except Else Finally

Python’s exception-handling mechanism is a powerful feature that allows developers to write more robust and reliable code. The “try-except” statement is a common construct used in Python for handling exceptions. However, there are additional statements that can be used with “try-except” to provide more control over the exception-handling process. In this article, we will explore the “try-except-else-finally” statement and provide examples of how it can be used.

Python Try Except Else Finally- Beginner python tutorials - 21 SCODES

What is the try-except-else-finally statement?

The try-except-else-finally statement is an extension of the basic “try-except” statement in Python. The “else” and “finally” blocks are added to provide additional functionality to the exception handling process.


The “else” block is executed when no exceptions are raised in the “try” block. It is typically used to handle the normal flow of execution, i.e., code that should be executed if no exceptions are raised. 

The “finally” block is executed regardless of whether an exception is raised or not. It is used to perform any cleanup operations that need to be done, such as closing files or database connections.


The basic syntax of the try-except-else-finally statement is as follows:

try:
# code that might raise an exception
except ExceptionType:
# code to handle the exception
else:
# code to execute if no exceptions are raised
finally:
# code to execute regardless of whether an exception is raised or not

Using try-except-else-finally with examples

Let’s explore how to use the try-except-else-finally statement with some examples. In this example, we will try to open a file and read its contents. If the file does not exist, we will catch the FileNotFoundError exception and print an error message. If the file exists, we will read its contents and print them to the console. 

Finally, we will close the file in the “finally” block:

try:
with open('example.txt', 'r') as f:
contents = f.read()
except FileNotFoundError:
print("The file does not exist.")
else:
print(contents)
finally:
f.close()

In this example, we are using the “with” statement to open the file, which ensures that the file is closed after we are done reading its contents. If the file exists, the contents are read and printed to the console. 

If the file does not exist, the FileNotFoundError exception is caught, and the error message is printed. Finally, we close the file in the “finally” block.

Another common use case for the try-except-else-finally statement is to catch and handle division by zero errors. In this example, we will try to divide two numbers, and if the denominator is zero, we will catch the ZeroDivisionError exception and print an error message. If the division is successful, we will print the result to the console. 

Finally, we will print a message to indicate that the operation is complete:

try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(result)
finally:
print("Operation complete.")

In this example, we are trying to divide 10 by 2, which is a valid division. If the division is successful, the result is printed to the console. If a ZeroDivisionError exception is raised, the error message is printed. Finally, we print a message to indicate that the operation is complete.

 

Conclusion

The try-except-else-finally statement is a powerful feature in Python that allows developers to have more control over the exception handling process. By using the “else” and “finally” blocks in addition to the “try” and “except” blocks, developers can write more robust and reliable code that can handle a wide range of exceptions.


The “else” block is executed when no exceptions are raised, allowing developers to execute code that should be executed when the normal flow of execution is not interrupted by an exception. The “finally” block is executed regardless of whether an exception is raised or not, allowing developers to perform any necessary cleanup operations, such as closing files or database connections.


In this article, we provided examples of how to use the try-except-else-finally statement in Python. We showed how to catch and handle FileNotFoundError and ZeroDivisionError exceptions, and how to perform cleanup operations using the “finally” block. By following these examples, developers can improve the reliability and robustness of their code by handling exceptions more effectively.

gp

Are you looking to learn a programming language but feeling overwhelmed by the complexity? Our programming language guide provides an easy-to-understand, step-by-step approach to mastering programming.

Leave a Reply

Your email address will not be published. Required fields are marked *