Python Program to Catch Multiple Exceptions in One Line
In Python, an exception is an error that occurs during the execution of a program. When an exception is raised, it interrupts the normal flow of the program and Python creates an instance of the corresponding exception class. If the exception is not handled, the program will terminate with an error message.
Some common examples of exceptions in Python include TypeError, ValueError, NameError, and ZeroDivisionError. These exceptions are raised when the program encounters an operation that is invalid or impossible to perform, such as dividing a number by zero or trying to access a variable that has not been defined.
Python Code :
The below Python program that catches multiple exceptions in one line:
# Define a function that might raise multiple exceptions
def divide(x, y):
try:
result = x / y
except (ZeroDivisionError, TypeError) as e:
print(f"Caught exception: {e}")
result = None
return result
# Call the function with different inputs to test it
print(divide(10, 2))
print(divide(10, 0))
print(divide(10, "2"))
Output:
5.0
Caught exception: division by zero
None
Caught exception: unsupported operand type(s) for /: 'int' and 'str'
None
In this program, we define a function called divide that takes two arguments, x and y, and returns their quotient if y is not zero and y is a number.
We use a try block to attempt the division and catch any exceptions that might be raised. In the except block, we catch both ZeroDivisionError and TypeError exceptions using a single tuple. If either exception is raised, we print a message that indicates which exception was caught, and we set the result to None.
We then return the result of the division, which will be either the quotient or None, depending on whether an exception was raised.
Finally, we call the divide function with different inputs to test it. We pass in valid inputs, an input that will raise a ZeroDivisionError, and an input that will raise a TypeError. The function catches the exceptions as expected and returns the appropriate result in each case.