User Tools

Site Tools


python_exceptions

Python Exceptions

Introduction

In Python, exceptions are a mechanism for handling errors and unexpected situations that arise during program execution. When an error occurs, Python raises an exception, which can be caught and handled by the program or propagated up the call stack. Understanding how to use exceptions effectively is crucial for writing robust and reliable Python code. This summary explores the concept of exceptions in Python and how they are used to handle errors.

For more information, refer to the Python documentation on errors and exceptions.

Exception Handling

Exception handling in Python involves using try-except blocks to catch and handle exceptions that may occur during program execution. The try block contains the code that may raise an exception, while the except block handles the exception if it occurs. Python also provides the option to specify different except blocks for different types of exceptions, allowing for fine-grained error handling. Here's an example:

```python try:

   result = 10 / 0
except ZeroDivisionError:
   print("Division by zero error")
```

For more information, refer to the Python documentation on the try statement.

Raising Exceptions

Python allows developers to raise exceptions explicitly using the raise statement. This allows for custom error handling and signaling exceptional conditions within the code. Developers can raise built-in exceptions or create custom exception classes by subclassing the built-in Exception class. Here's an example:

```python def divide(x, y):

   if y == 0:
       raise ZeroDivisionError("Division by zero")
   return x / y

try:

   result = divide(10, 0)
except ZeroDivisionError as e:
   print(e)
```

For more information, refer to the Python documentation on raising exceptions.

Handling Multiple Exceptions

Python allows handling multiple exceptions in a single except block or using multiple except blocks to handle different types of exceptions separately. This allows for more granular error handling based on the specific error conditions that may arise. Here's an example:

```python try:

   result = 10 / 0
except (ZeroDivisionError, ValueError):
   print("Error occurred")

try:

   result = int("abc")
except ValueError:
   print("ValueError occurred")
```

For more information, refer to the Python documentation on handling exceptions.

Finally Block

The finally block in Python is used to define cleanup actions that must be executed regardless of whether an exception occurs. This block is commonly used to release external resources, such as file handles or network connections, that were acquired in the try block. The code in the finally block is guaranteed to execute, even if an exception is raised or caught. Here's an example:

```python try:

   file = open("example.txt", "r")
   # Perform file operations
except FileNotFoundError:
   print("File not found")
finally:
   if 'file' in locals():
       file.close()
```

For more information, refer to the Python documentation on the finally block.

Code Example: Exception Handling

```python try:

   result = 10 / 0
except ZeroDivisionError:
   print("Division by zero error")
```

For more information, refer to the Python documentation on the try statement.

Code Example: Raising Exceptions

```python def divide(x, y):

   if y == 0:
       raise ZeroDivisionError("Division by zero")
   return x / y

try:

   result = divide(10, 0)
except ZeroDivisionError as e:
   print(e)
```

For more information, refer to the Python documentation on raising exceptions.

Code Example: Handling Multiple Exceptions

```python try:

   result = 10 / 0
except (ZeroDivisionError, ValueError):
   print("Error occurred")

try:

   result = int("abc")
except ValueError:
   print("ValueError occurred")
```

For more information, refer to the Python documentation on handling exceptions.

Code Example: Finally Block

```python try:

   file = open("example.txt", "r")
   # Perform file operations
except FileNotFoundError:
   print("File not found")
finally:
   if 'file' in locals():
       file.close()
```

For more information, refer to the Python documentation on the finally block.

python_exceptions.txt · Last modified: 2024/04/28 03:13 (external edit)