What is anException?Exceptions are noting but the errors detected during execution of theprogram. 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 torespond without crashing. The program creates an “exception” objectthat contains information about the error. The process of responding tothis 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 Blocktry:#Code that may raise an exceptionresult = 10 / 0except ZeroDivisionError:# Handling specific exceptionprint("Cannot divide by zero!")
6.
Handling Multiple ExceptionsHandlingmultiple exceptions means being ready for different kinds of errors,and knowing exactly how to respond to each — just like solving differentproblems 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 specificallyhandled.raise KeywordThe raise keyword in Python is used to manually trigger an exception. It tells theprogram: “Something went wrong — stop and handle this issue.”custom exceptionA custom exception is a user-defined error type that you create to handlespecific 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 ExceptionsBaseExceptionThe rootclass for all exceptions inPython.Popular Built-ins• TypeError• NameError• IndexError• IOErrorCommon Exceptions•ArithmeticError•LookupError•ValueError