Python Errors and Exceptions

In this section, we'll explore how Python handles errors and exceptions. Errors can occur during the execution of a program, but Python provides mechanisms to handle them gracefully. We’ll dive into the different types of errors, how to handle exceptions with the try-except block, and more advanced exception-handling techniques.



Types of Errors in Python

In Python, errors are classified into different types. These errors can be broadly categorized into two groups: syntax errors and runtime errors. Here's an overview of each type:

  • Syntax Errors: Occur when the Python interpreter encounters invalid syntax. These errors prevent the program from running. For example, missing parentheses or incorrect indentation.
  • Runtime Errors: Occur when the program runs, but encounters an issue that prevents further execution, such as division by zero, accessing an undefined variable, etc.
  • Logic Errors: These errors don't cause the program to crash but lead to incorrect results due to flawed logic in the code.

1. Example of a Syntax Error

A syntax error happens when Python cannot understand the code due to incorrect formatting. It might be caused by missing punctuation, parentheses, or improper indentation.

python
# Missing closing parenthesis causes a syntax error
print("Hello, world!"

Output:

SyntaxError: unexpected EOF while parsing

2. Example of a Runtime Error

A runtime error occurs when the program is running, but something goes wrong during execution. This could be caused by invalid operations like dividing by zero or trying to access an undefined variable.

python
# Division by zero causes a runtime error
x = 10
y = 0
print(x / y)

Output:

ZeroDivisionError: division by zero

3. Example of a Logic Error

A logic error occurs when the code runs without crashing, but the results are incorrect due to an error in the logic of the program. The program will not raise an exception, but the output will not be what you expect.

python
# Logic error: incorrect calculation of average
numbers = [10, 20, 30, 40, 50]
sum_of_numbers = sum(numbers)
count_of_numbers = len(numbers)
average = sum_of_numbers // count_of_numbers  # Incorrect use of integer division
print(f"The average is {average}")

Output:

The average is 30

In the above code, integer division was used for calculating the average, which causes the result to be incorrect. It should have used normal division ("/") instead of floor division ("//").


What Are Exceptions?

Exceptions are a way for Python to indicate that an error has occurred. Instead of letting the program continue running in an invalid state, Python raises exceptions to signal that something unexpected happened. Once raised, an exception can either be handled by a programmer or, if left unhandled, it can cause the program to crash.

Why Do Exceptions Happen?

Exceptions happen due to various errors in the code, such as:

  • Incorrect operations: Operations that are not supported by the data type, like trying to add a string and an integer.
  • Accessing out-of-range indices: Trying to access elements of a sequence using indices that do not exist.
  • Invalid input: Passing incorrect types or values to functions, such as trying to convert a non-numeric string to an integer.
  • File operations: Attempting to open, read, or write to a file that does not exist.

1. Example: Adding a String and an Integer

Let's look at a situation where an exception is raised due to an invalid operation. In this example, we try to add a string and an integer, which is not allowed in Python. This results in a TypeError.

python
# Invalid operation: adding a string and an integer
name = "Tom"
age = 30
greeting = name + age
print(greeting)

Output:

TypeError: can only concatenate str (not "int") to str

In this case, Python raises a TypeError because it's not valid to add a string and an integer directly. To fix this, we could convert the integer to a string using str(age) before concatenating.

2. Example: Accessing an Out-of-Range Index

Another common exception is the IndexError, which occurs when you try to access an element of a list (or other sequence) using an index that doesn't exist.

python
# Accessing an index that is out of range
numbers = [1, 2, 3]
print(numbers[5])  # This index does not exist

Output:

IndexError: list index out of range

In this example, Python raises an IndexError because the list numbers has only 3 elements (indices 0, 1, and 2), but the code attempts to access index 5, which does not exist.

3. Example: Converting an Invalid String to an Integer

A ValueError happens when a function receives an argument of the right type but with an inappropriate value. For example, trying to convert a non-numeric string to an integer causes this error.

python
# Attempting to convert a non-numeric string to an integer
user_input = "abc"
number = int(user_input)
print(number)

Output:

ValueError: invalid literal for int() with base 10: 'abc'

Here, Python raises a ValueError because the string "abc" cannot be converted to an integer. To avoid this, you can validate the input before conversion or handle the exception using try-except blocks.


Frequently Asked Questions

What are errors and exceptions in Python?

Errors are issues that prevent a program from running, while exceptions are runtime issues that can be caught and handled to prevent crashes.


What is the difference between errors and exceptions in Python?

Errors usually prevent a program from running (like syntax errors), while exceptions can occur during runtime and can be handled using try-except blocks.


How do I handle exceptions in Python?

Use a try-except block. For example:try:
  # some code that may raise an exception
except Exception as e:
  # handle the exception


What is the purpose of the 'finally' block?

The 'finally' block is always executed, regardless of whether an exception occurred. It's useful for code that must run for cleanup, such as closing a file or releasing resources.


Can I create custom exceptions in Python?

Yes, you can create custom exceptions by subclassing Python’s built-in Exception class:
class MyCustomError(Exception):
  pass



What's Next?

In the next section, we will dive deeper into exception handling in Python. You’ll learn how to use the try-except blocks to handle errors, ensure your programs run smoothly, and prevent them from crashing unexpectedly.