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
- 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. - 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. - 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.