Python for Beginners (Error and Exception Handling in Python)

Kalana De Silva
3 min readJun 12, 2024

--

Welcome back to our Python Programming series! In the previous article, we explored file handling. Today, we’ll dive into error and exception handling, which allows us to manage and respond to errors in our programs gracefully. Let’s get started!

What are Exceptions?

Exceptions are events that disrupt the normal flow of a program. In Python, exceptions are objects that are raised when an error occurs. If not handled, an exception will cause the program to terminate.

Common Exceptions

Here are some common exceptions you might encounter in Python:

SyntaxError: Invalid syntax.

TypeError: Invalid operation for the given data type.

ValueError: Invalid value.

IndexError: Index out of range.

KeyError: Key not found in a dictionary.

FileNotFoundError: File not found.

Handling Exceptions

We use try, except, else, and finally blocks to handle exceptions in Python.

Basic Try-Except Block

The try block contains the code that might raise an exception, and the except block contains the code to handle the exception.

try:
numerator = 10
denominator = 0
result = numerator / denominator
except ZeroDivisionError:
print("Error: Cannot divide by zero.")

Output:

Error: Cannot divide by zero.

Handling Multiple Exceptions

You can handle multiple exceptions by specifying multiple except blocks.

try:
value = int("abc")
except ValueError:
print("Error: Invalid value.")
except TypeError:
print("Error: Invalid type.")

Output:

Error: Invalid value.

Using Else

The else block is executed if no exceptions are raised in the try block.

try:
value = int("123")
except ValueError:
print("Error: Invalid value.")
else:
print("No errors. The value is:", value)

Output:

No errors. The value is: 123

Using Finally

The finally block is executed no matter what, even if an exception is raised. It is often used for cleanup actions.

try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close()
print("File closed.")

Output:

Error: File not found.
File closed.

Raising Exceptions

You can raise exceptions manually using the raise statement.

def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age

try:
age = check_age(-1)
except ValueError as e:
print("Error:", e)

Output:

Error: Age cannot be negative.

Custom Exceptions

You can define your own exceptions by creating a class that inherits from the built-in Exception class.

class CustomError(Exception):
def __init__(self, message):
self.message = message

def do_something(value):
if value < 0:
raise CustomError("Value cannot be negative.")

try:
do_something(-1)
except CustomError as e:
print("Error:", e.message)

Output:

Error: Value cannot be negative.

Example: Handling Multiple Exceptions

Here’s an example that handles different types of exceptions.

try:
file = open("example.txt", "r")
content = file.read()
value = int(content)
except FileNotFoundError:
print("Error: File not found.")
except ValueError:
print("Error: Cannot convert file content to an integer.")
except Exception as e:
print("An unexpected error occurred:", e)
finally:
print("Execution completed.")

Summary

In this article, we learned about error and exception handling in Python. We covered the use of try, except, else, and finally blocks, how to raise exceptions, and how to create custom exceptions. Proper error handling is crucial for building robust and user-friendly programs.

In the next article, we’ll explore the principles of object-oriented programming (OOP) in Python. Stay tuned for more Python fun every Monday, Wednesday, and Friday at 7 PM. Happy coding!

For real-time discussions, industry insights, and more, connect with me on LinkedIn. Let’s grow together!

🔗 Connect on LinkedIn

Thank you for being part of this learning journey!

--

--

Kalana De Silva

MERN | Laraval | Postman Student Expert | Full-Stack | Azure | Dev | IT Enthusiast | undergraduate at SLIIT