0% found this document useful (0 votes)
5 views4 pages

Python Exception Handling Guide

Uploaded by

Amit Kamble
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)
5 views4 pages

Python Exception Handling Guide

Uploaded by

Amit Kamble
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

Exception Handling in Python – Notes

1. What is an Exception?

An exception is an error that occurs during the execution of a program and stops it unless handled.

Common Exceptions:

• ZeroDivisionError

• ValueError

• TypeError

• FileNotFoundError

2. Why Use Exception Handling?

To prevent the program from crashing and provide a meaningful message to the user.

3. try–except Block

Use try-except when you think a block of code may raise an error.

Example:

try:

a = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero!")


4. try–except–else

The else block runs only if no exception occurs.

Example:

try:

num = int(input("Enter number: "))

except ValueError:

print("Invalid input")

else:

print("You entered:", num)

5. try–except–finally

The finally block runs whether or not an exception occurs. Useful for cleanup.

Example:

try:

f = open("[Link]")

except FileNotFoundError:

print("File not found!")

finally:
print("Task completed.")

6. Raising Exceptions

You can raise your own exceptions using raise.

Example:

age = -1

if age < 0:

raise ValueError("Age cannot be negative")

7. Creating Custom Exceptions

You can define custom exception classes.

Example:

class MyError(Exception):

pass

try:

raise MyError("Custom error occurred")

except MyError as e:
print(e)

Summary:

• Use try–except to handle errors gracefully.

• else runs if no error.

• finally always runs.

• raise is used to trigger errors manually.

You might also like