0% found this document useful (0 votes)
12 views5 pages

Python Exception Handling Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views5 pages

Python Exception Handling Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

## 🧩 **1. What is Exception Handling in Python?

**
**Exception Handling** is a mechanism that allows a program to deal with runtime errors
(exceptions) gracefully, instead of crashing abruptly.
It ensures the normal flow of execution even when an error occurs.

---

## ⚙️ **2. Common Causes of Exceptions**


Some common exceptions include:

| Exception | Description |
| ------------------- | ------------------------------------------- |
| `ZeroDivisionError` | Dividing a number by zero |
| `ValueError` | Invalid value passed to a function |
| `TypeError` | Operation applied to an incorrect data type |
| `IndexError` | Index out of range in lists or tuples |
| `KeyError` | Accessing a non-existent dictionary key |
| `FileNotFoundError` | File not found during file operations |
| `ImportError` | Module not found during import |
| `AttributeError` | Invalid attribute reference |

---

## 🧱 **3. Syntax of Exception Handling**


```python
try:
# Code that may raise an exception
except ExceptionType:
# Code that runs if exception occurs
else:
# Code that runs if no exception occurs
finally:
# Code that runs no matter what
```

---

## 🧮 **4. Example: Basic Exception Handling**


```python
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter a number.")
else:
print("No exceptions occurred!")
finally:
print("Execution completed.")
```

**Explanation:**

* `try`: Code that might throw an exception.


* `except`: Catches specific exceptions.
* `else`: Runs only if no exceptions occur.
* `finally`: Always runs, useful for cleanup (like closing files).

---

## ⚖️ **5. Catching Multiple Exceptions**


You can catch multiple exceptions in one block:

```python
try:
x = int("abc")
except (ValueError, TypeError) as e:
print("An error occurred:", e)
```

---

## 💡 **6. Using `as` Keyword**


You can store the exception in a variable using `as`:

```python
try:
with open("[Link]", "r") as f:
data = [Link]()
except FileNotFoundError as e:
print(f"File not found: {e}")
```

---

## 🔄 **7. Raising Exceptions**


You can manually raise an exception using `raise`:

```python
def divide(a, b):
if b == 0:
raise ValueError("Denominator cannot be zero")
return a / b

try:
print(divide(5, 0))
except ValueError as e:
print("Caught Exception:", e)
```

---

## 🧰 **8. Creating Custom Exceptions**


You can define your own exceptions by inheriting from `Exception`:

```python
class NegativeNumberError(Exception):
"""Custom exception for negative numbers."""
pass

def check_number(n):
if n < 0:
raise NegativeNumberError("Negative numbers are not allowed")
else:
print("Number is valid")

try:
check_number(-10)
except NegativeNumberError as e:
print(e)
```

---

## 🧭 **9. Nested Exception Handling**


You can have `try-except` blocks inside another `try` block.

```python
try:
try:
x = int("abc")
except ValueError:
print("Inner block caught ValueError")
y=1/0
except ZeroDivisionError:
print("Outer block caught ZeroDivisionError")
```

---

## 🧠 **10. Best Practices for Exception Handling**


| ✅ Do | ❌ Avoid |
| -------------------------------------------------------------------------- |
------------------------------------------------------- |
| Catch **specific exceptions** (e.g., `ValueError`, `KeyError`) | Avoid using bare
`except:` without specifying the error |
| Use **`finally`** for cleanup (close files, release resources) | Don’t suppress exceptions
silently |
| Include **meaningful error messages** | Avoid catching generic
`Exception` unless necessary |
| Log exceptions using the **`logging`** module instead of just printing | Don’t use exceptions
for flow control |
| Create **custom exceptions** for specific application needs | Avoid deeply nested
`try-except` blocks |
| Use **context managers** (`with` statement) for file and resource handling | Don’t ignore return
values or error codes |

---

## 🧾 **11. Example with Logging and Cleanup**


```python
import logging

[Link](level=[Link], filename="[Link]")

def read_file(filename):
try:
with open(filename, "r") as file:
data = [Link]()
print(data)
except FileNotFoundError as e:
[Link](f"File not found: {e}")
print("Error: The file does not exist.")
except Exception as e:
[Link](f"Unexpected error: {e}")
print("An unexpected error occurred.")
finally:
print("Operation finished.")

read_file("[Link]")
```

---

## 🧾 **12. Summary**
| Keyword | Purpose |
| --------- | --------------------------------------- |
| `try` | Contains code that may raise exceptions |
| `except` | Handles exceptions |
| `else` | Runs when no exception occurs |
| `finally` | Runs always (used for cleanup) |
| `raise` | Manually trigger exceptions |
| `assert` | Debugging tool to test assumptions |

You might also like