What is anException?
Exceptions are noting but the errors detected during execution of the
program. They interrupt the normal flow of a program’s instructions.
What is Exception handling ?
The machine expects that something might go wrong and knows how to
respond without crashing. The program creates an “exception” object
that contains information about the error. The process of responding to
this exception is called “exception handling”.
3.
Why Exception Handling?
•- To prevent program crashes.
• - To handle errors gracefully.
• - To improve debugging and error tracing.
• - To ensure the program continues or fails safely.
Basic Try-Except Block
try:
#Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Handling specific exception
print("Cannot divide by zero!")
6.
Handling Multiple Exceptions
Handlingmultiple exceptions means being ready for different kinds of errors,
and knowing exactly how to respond to each — just like solving different
problems in everyday life.
8.
Else Clause:
else`: Runsif no exceptions occur.
Finally Clause:
`finally`: Always executes, whether exception occurred or not.
Catch-All Exception Handling:
You can use a general except block to catch any exception that wasn't specifically
handled.
raise Keyword
The raise keyword in Python is used to manually trigger an exception. It tells the
program: “Something went wrong — stop and handle this issue.”
custom exception
A custom exception is a user-defined error type that you create to handle
specific problems in your program more clearly and meaningfully.
9.
Raising Exceptions
• defbake_cake(eggs):
• if eggs == 0:
• # Raise an exception if no eggs
• raise ValueError("You need at least one egg to bake a cake!")
• print("Cake is baking...")
• # Now let's handle the exception when calling the function
• try:
• bake_cake(0) # Trying to bake with 0 eggs
• except ValueError as e:
• print("Error:", e)
10.
Understanding Exceptions
BaseException
The rootclass for all exceptions in
Python.
Popular Built-ins
• TypeError
• NameError
• IndexError
• IOError
Common Exceptions
•ArithmeticError
•LookupError
•ValueError
Best Practices
• -Catch specific exceptions.
• - Avoid bare excepts (except:)
• - Clean up resources (use finally or with)
• - Log errors for debugging.