- Published on
Mastering Python Try-Except
try-except
In Python, an exception is an event that occurs during the execution of a program that disrupts the normal flow of the program's instructions. It is important to handle exceptions. When they occur, that is why Python comes with a built-in try…except
syntax, with which you can handle exceptions. The way it works is by placing the operation that can raise an exception inside the try
block and place the code that handles the exceptions in the except
block.
Here's the syntax of try...except
block:
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
Python comes with a built-in exceptions such as ZeroDivisionError
, NameError
, TypeError
, ValueError
, IndexError
, KeyError
, and many more as well as allow developers to create Self-defined exceptions .
Here's a simple example that shows how to handle ZeroDivisionError
:
try:
result = 100 / 0
print(result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
In the above example within the try block, we are trying to divide a 100 by 0 which would raise a ZeroDivisionError. However, we have put the code result = 100 / 0
inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped and exception is caught by the except block, and an error message is printed.
Handling Any Exception:
To handle any exception you just add except
without specifying the exception type that way you can handle any type of exception but it is not generally recommended you should allways handle specific exceptions when possible.
Here's the syntax for handling any exception
try:
# Code that may raise an exception
except:
# Code to handle any exception
Python try with else clause
You can include an else
block after the try-except
block to instruct a program to execute a certain block of code only if there is no exception.
Let's look at an example:
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
result = a / b
except ValueError:
print("Invalid input. Please enter numbers only.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("The result is:", result)
Python try...finally
Optionally, you can add the finally block to the try..except
The The finally block always executes regardless of whether an exception occurs or not. Here's an example that demonstrates the usage of the try...finally
block for file handling in Python:
def read_file(file_path):
try:
file = open(file_path, 'r')
content = file.read()
print(f"File content: {content}")
except FileNotFoundError:
print("Error: File not found!")
finally:
if 'file' in locals():
file.close()
print("File closed successfully.")
# Example usage
file_path = "example.txt"
read_file(file_path)
In the above example we defined a function read_file()
the function accepts file_path
as argument and inside the try
block we are trying to open the file given by file_path
in read mode using the open()
function and print the content of the file if the file is not found or FileNotFoundError
occurs the exception is caught by the except block, and an error message is printed. Regardless of whether an exception occurs or not, the finally
block will be executed to ensure that the file is closed properly.