Skip to main content
Published on

Exceptions in Python

Share:

Introduction

Exceptions are a fundamental part of many programming languages, and Python is no exception. They provide a structured way to handle errors and unexpected situations.

What are Exceptions?

In Python, an exception is an event that occurs during the execution of a program when something goes outside of what is expected. These events can be caused by various factors, such as illegal operations, data problems, or even external failures.

Handling Exceptions

The try block allows you to test a block of code to see if it raises any errors. The except block contains the code that will be executed if the try block results in an exception.

Basic Example

try:
result = 10 / 0
except ZeroDivisionError:
print('You cannot divide by zero!')

In the code above, we try to divide 10 by zero, which will raise a ZeroDivisionError exception. Instead of terminating the program's execution, the code in the except block will be executed.

Using Multiple Except Blocks

You can use multiple except blocks to handle different types of exceptions.

try:
  readFile = open('Files-Write-and-Read.txt', 'r')
  print(readFile.read())
except FileNotFoundError:
  print('The file was not found.')
except IOError:
  print('There was an error reading the file.')
else:
  print('The file was read successfully.')
  readFile.close()
finally:
  print('This block will always be executed, regardless of whether an exception occurred or not.')

Conclusion

Exceptions in Python are a powerful tool that allows programmers to handle errors effectively and in a structured way. By learning to use them correctly, you can create more robust and resilient code.

Happy coding!