0% found this document useful (0 votes)
14 views4 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 DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 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 DOCX, PDF, TXT or read online on Scribd

🐍 Python Exception Handling

1. What is an Exception?

 An exception is an error that occurs during program execution.

 Example: dividing by zero, accessing a file that doesn’t exist.

👉 Without handling, the program will stop suddenly.


👉 With exception handling, we can catch the error and continue the
program.

Example:
print(10/0) # Error: Division by zero

2. Why Exception Handling?


- To prevent program crash.
- To handle errors smoothly.
- To give user-friendly messages/ To show a meaningful message to the
user.

3. The try-except Statement


Code that may cause an error → inside try.
Handling code → inside except.

Example:
try:
a = int("hello")
except ValueError:
print("Conversion not possible!")
4. Multiple except Blocks
We can handle different types of errors separately.

Example:
try:
x = 10/0
except ValueError:
print("Value error occurred.")
except ZeroDivisionError:
print("Cannot divide by zero!")

5. Catching All Exceptions


Use only except: to catch any kind of error.

Example:
try:
num = int("abc")
except:
print("Some error occurred!")

6. The else Clause


The else block runs if no error occurs.

Example:
try:
num = int("100")
print("Converted:", num)
except ValueError:
print("Invalid number!")
else:
print("No error happened!")
7. The finally Clause
The finally block always executes, whether there is an error or not.
Used for closing files, freeing resources.

Example:
try:
f = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found!")
finally:
print("This will always run.")

8. Raising Exceptions (raise)


We can manually raise errors using raise.

Example:
age = 16
if age < 18:
raise ValueError("You must be 18 or older.")

9. Creating User-Defined Exceptions


We can make our own error class.

Example:
class UnderAgeError(Exception):
pass

try:
age = 15
if age < 18:
raise UnderAgeError("You are underage!")
except UnderAgeError as e:
print("Custom Exception:", e)
10. Common Exceptions in Python

- ZeroDivisionError → when dividing by zero


- ValueError → wrong type conversion
- TypeError → wrong type of operation
- IndexError → index out of range
- KeyError → key not found in dictionary
- FileNotFoundError → file does not exist

Example (IndexError):
list1 = [1, 2, 3]
print(list1[5]) # IndexError

🎯 Quick Summary

- try → write risky code.


- except → handle error.
- else → runs only if no error.
- finally → runs always.
- raise → generate own error.
- Custom Exception → create your own error class.

You might also like