Python Exceptions
Introduction
When writing code in Python, it is important to know how to handle errors and exceptions that may occur during runtime. An exception is an error that occurs while a Python program is running. This can happen for a variety of reasons, such as invalid input, network problems, or file I/O errors. Exceptions are raised and can be caught and handled by programs, allowing them to gracefully recover from errors.
Syntax
Exceptions are raised using the `raise` statement, followed by the name of the exception class. Here’s an example:
“`python
raise Exception(“Something went wrong.”)
“`
This creates a new instance of the `Exception` class and raises it, with the message “Something went wrong.”
Catching Exceptions
To catch an exception, you use a `try` statement. The `try` block contains the code that may raise an exception, and the `except` block catches the exception and handles it.
“`python
try:
# some code that may raise an exception
except Exception as e:
# handle the exception
“`
The `except` block catches the exception, assigns it to the variable `e`, and then handles it. You can catch specific exceptions by specifying the exception class in the `except` block.
“`python
try:
# some code that may raise an exception
except ValueError:
# handle the ValueError
except IndexError:
# handle the IndexError
“`
In this example, the `except` block catches either a `ValueError` or an `IndexError`. If an exception is raised that is not caught by any `except` blocks, the program will terminate with an error message.
Raising Your Own Exceptions
You can also raise your own exceptions by creating a new exception class. An exception class is simply a subclass of the `Exception` class, with some additional methods and properties added as needed.
“`python
class MyException(Exception):
pass
raise MyException(“My custom exception message.”)
“`
This creates a new exception class `MyException` that can be raised like any other exception. To catch this exception, you would use the class name in the `except` block.
“`python
try:
raise MyException(“My custom exception message.”)
except MyException as e:
print(e)
“`
Exception Hierarchy
In Python, exceptions are organized into a hierarchy of classes. The base class for all exceptions is `BaseException`, which is itself a subclass of `Exception`. `Exception` is the base class for most common exceptions, such as `ValueError`, `TypeError`, and `IndexError`.
You can catch exceptions from multiple levels of the hierarchy by catching the base exception class first, and then catching the more specific exceptions later.
“`python
try:
# some code that may raise an exception
except BaseException as e:
# handle the exception
except ValueError:
# handle the ValueError
“`
This will catch all exceptions that are subclasses of `BaseException`, including `ValueError`.
Conclusion
Python exceptions provide a powerful way to handle errors and exceptions in your code. By raising and catching exceptions, you can gracefully recover from errors and keep your program running smoothly. Understanding how exceptions work and how to handle them is an essential part of writing robust and reliable Python code.