Exception Handling
Exception Handling
1. What is an Error?
Types of Errors:
1. Syntax Errors
2. Syntax Errors
• Errors in the structure of the code (spelling, missing colons, brackets, etc.).
Example:
Output:
• Happen due to invalid actions like dividing by zero or using wrong data types.
Example:
a=5/0
Output:
5. Types of Exceptions
ZeroDivisionError Division by 0 10 / 0
You can create your own exceptions by defining a class that inherits from Python's Exception
class.
Example 1:
class NegativeNumberError(Exception):
pass
number = -5
if number < 0:
Example 2:
python
CopyEdit
class TooShortError(Exception):
pass
name = "Al"
if len(name) < 3:
Without Handling:
With Handling:
• Prevents program from crashing
Throwing an Exception
Example:
python
CopyEdit
age = -1
if age < 0:
Catching an Exception
8. Raising Exceptions
a. raise Statement
Example:
python
CopyEdit
marks = -50
if marks < 0:
Example:
python
CopyEdit
age = -3
9. Handling Exceptions
Python uses the try-except block to catch and fix errors without crashing.
Syntax:
python
CopyEdit
try:
# risky code
except ExceptionType:
Example:
python
CopyEdit
try:
print(10 / x)
except ZeroDivisionError:
Example:
python
CopyEdit
try:
except ValueError:
print("Invalid input!")
else:
print("You entered:", x)
Example:
python
CopyEdit
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
Term Use
python
CopyEdit
class AgeError(Exception):
pass
try:
except ValueError:
print("Please enter a valid number!")
except AssertionError as e:
print("Assertion Error:", e)
except AgeError as e:
print("Custom Error:", e)
else:
print("Age is valid.")
finally: