Q} How to handle multiple exceptions.
Exception handling is a mechanism in
programming languages that allows you to handle and recover from exceptional
events or errors that may occur during program execution. In Python, exceptions
are raised when errors or exceptional situations occur while executing code.
These exceptions can be predefined built-in exceptions or custom exceptions
defined by the programmer.
When
you anticipate that a specific piece of code may raise an exception, you can
enclose it within a try block. The code inside the try block is monitored for
any exceptions. If an exception occurs within the try block, the flow of
execution immediately jumps to the corresponding except block that matches the
exception type.
To handle multiple exceptions in Python, you have two
common approaches:
1. Multiple except blocks: In this approach, you can have
multiple except blocks, with each block handling a specific exception type. The
except block that matches the raised exception type is executed, and the flow
of execution continues after the last except block. You can add as many except
blocks as needed to handle different exception types. It's important to order
the except blocks in a way that prioritizes more specific exceptions before
more general ones, as Python will match the exceptions sequentially and execute
the first matching except block it encounters.
2. Single except block with multiple exception types: In this approach, you can group
multiple exception types together within a tuple and handle them in a single except
block. If any of the specified exceptions occur, the code within the except
block is executed. This approach allows you to handle different exceptions in
the same way. You can include as many exception types as needed within the
tuple.
Regardless
of the approach you choose, it's important to handle exceptions properly within
the except block. You can include code to handle the exception, log error
messages, perform cleanup operations, or take appropriate actions to handle the
exceptional situation gracefully.
If
no exception occurs within the try block, the except block(s) will be skipped,
and the program will continue executing the code after the last except block.
In
addition to except blocks, you can also include an optional finally block. The finally
block is executed whether an exception occurs or not. It allows you to perform
cleanup operations or release resources that need to be executed regardless of
exceptions.
try: # Code that may raise exceptions a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) result = a / b print("The result is:", result) except ValueError: print("Invalid input. Please enter a valid integer.") except ZeroDivisionError: print("Cannot divide by zero. Please enter a non-zero value.") except Exception as e: print("An error occurred:", str(e))