Errors and Exception Handling in Python

Introduction

When you write a program, sometimes things don’t go as planned. Errors can happen for many reasons: maybe you tried to divide by zero, or perhaps you tried to open a file that doesn’t exist. Python has a way to handle these errors so your program can keep running smoothly. This is called Error and Exception Handling.

Types of Errors

  1. Syntax Errors: These are mistakes in the way your code is written. Python can’t understand what you want it to do, so it stops running the program.

    print("Hello World)

    The above code will cause a syntax error because the closing quotation mark is missing.
  2. Runtime Errors: These errors happen while the program is running. They can occur for many reasons, like trying to divide by zero or using a variable that hasn’t been defined.

    x = 10 / 0

    The above code will cause a runtime error because you can’t divide by zero.
  3. Logical Errors: These errors don’t stop your program from running, but they make it do the wrong thing. For example, using the wrong formula in a math problem.

    result = 10 * 2 # Instead of 10 + 2

    The code above will give you 20 instead of 12 because of a logical error.

Handling Exceptions

Python lets you handle runtime errors using a structure called try-except. This means you can try to do something, and if it causes an error, you can handle it in a way that won’t crash your program.

Basic Try-Except

Here’s an example:

try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")

In this code:

  • try is where you put the code that might cause an error.
  • except is where you handle the error.

Handling Multiple Exceptions

You can handle different types of errors separately:

try:
x = int("Hello")
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
print("You can't divide by zero!")

In this code:

  • If the error is because “Hello” can’t be converted to an integer, it prints “That’s not a number!”
  • If the error is a division by zero, it prints “You can’t divide by zero!”

Finally Block

You can also use a finally block to run code no matter what happens:

try:
x = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("This will run no matter what.")

The finally block will always execute, whether there was an error or not.

Real-Time Useful Examples

Example 1: User Input

When asking users for input, they might enter something that causes an error. Here’s how you can handle it:

try:
age = int(input("Enter your age: "))
print("You are", age, "years old.")
except ValueError:
print("Please enter a valid number.")

Example 2: File Handling

When working with files, you might try to open a file that doesn’t exist:

try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("The file does not exist.")
finally:
file.close()

Common Exception classes in Python

These are some of the common exception classes you might encounter in Python. The BaseException is the base class for all exceptions, and most user-defined exceptions are derived from the Exception class.

BaseException
 ├── SystemExit
 ├── KeyboardInterrupt
 ├── GeneratorExit
 └── Exception
      ├── StopIteration
      ├── StopAsyncIteration
      ├── ArithmeticError
      │    ├── FloatingPointError
      │    ├── OverflowError
      │    └── ZeroDivisionError
      ├── AssertionError
      ├── AttributeError
      ├── BufferError
      ├── EOFError
      ├── ImportError
      │    └── ModuleNotFoundError
      ├── LookupError
      │    ├── IndexError
      │    └── KeyError
      ├── MemoryError
      ├── NameError
      │    └── UnboundLocalError
      ├── OSError
      │    ├── BlockingIOError
      │    ├── ChildProcessError
      │    ├── ConnectionError
      │    │    ├── BrokenPipeError
      │    │    ├── ConnectionAbortedError
      │    │    ├── ConnectionRefusedError
      │    │    └── ConnectionResetError
      │    ├── FileExistsError
      │    ├── FileNotFoundError
      │    ├── InterruptedError
      │    ├── IsADirectoryError
      │    ├── NotADirectoryError
      │    ├── PermissionError
      │    ├── ProcessLookupError
      │    └── TimeoutError
      ├── ReferenceError
      ├── RuntimeError
      │    ├── NotImplementedError
      │    └── RecursionError
      ├── SyntaxError
      │    └── IndentationError
      │         └── TabError
      ├── SystemError
      ├── TypeError
      ├── ValueError
      │    └── UnicodeError
      │         ├── UnicodeDecodeError
      │         ├── UnicodeEncodeError
      │         └── UnicodeTranslateError
      └── Warning
           ├── DeprecationWarning
           ├── PendingDeprecationWarning
           ├── RuntimeWarning
           ├── SyntaxWarning
           ├── UserWarning
           ├── FutureWarning
           ├── ImportWarning
           ├── UnicodeWarning
           └── BytesWarning

In this example:

  • If the file doesn’t exist, it prints “The file does not exist.”
  • The finally block ensures that the file is closed if it was opened.

Conclusion

Understanding how to handle errors and exceptions is essential for writing reliable and user-friendly programs. By using try, except, and finally, you can make sure your program behaves correctly even when things go wrong.


I hope this helps! Let me know if you need any more examples or further explanations.

Data AI Admin

Senior AI Lead having overall Experience of 10+ years in IT, Data Science, Machine Learning, AI and related fields.

Related Posts

Exploring Different Pandas File Formats

Data handling and manipulation are fundamental in data analysis. Pandas, a powerful Python library, supports various file formats for reading, writing, and converting data. Understanding these formats and their benefits…

Read more

Making Beautiful Plots with Seaborn in Python

Welcome to the sixth tutorial in our series on data analysis with Python! In this article, we’ll introduce you to Seaborn, a powerful Python visualization library built on top of…

Read more

Leave a Reply

You Missed

Exploring Different Pandas File Formats

  • June 28, 2024
Exploring Different Pandas File Formats

Making Beautiful Plots with Seaborn in Python

  • June 28, 2024
Making Beautiful Plots with Seaborn in Python

Mastering Data Visualization with Matplotlib

  • June 28, 2024
Mastering Data Visualization with Matplotlib

Data Cleaning and Preprocessing with Pandas

  • June 27, 2024
Data Cleaning and Preprocessing with Pandas

Exploring Data with Pandas: Series and DataFrames

  • June 27, 2024
Exploring Data with Pandas: Series and DataFrames

NumPy : Basic Operations and Arrays

  • June 27, 2024
NumPy : Basic Operations and Arrays