Introduction:
Exception handling is a fundamental aspect of Python programming to manage errors gracefully. In this tutorial, we delve into handling exceptions without specifying a particular exception type. We demonstrate the use of a generic except block to catch any unanticipated exceptions. With a practical example, you’ll gain valuable insights into managing unforeseen errors in your Python code.
Code:
print("Handling exceptions without naming them")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print("Division performed successfully")
except ValueError:
print("Only INTEGERS should be entered")
except:
print(" OOPS.....SOME EXCEPTION RAISED")
Logic:
- Display the message “Handling exceptions without naming them” to indicate the purpose of the code.
- The try block is introduced to encapsulate the code that may raise exceptions during execution.
- The variable numerator is set to 50. The input is converted to an integer using int() and stored in the denom variable.
- If the user enters a valid integer value for the denominator, the program proceeds to calculate the quotient (numerator/denom). The message “Division performed successfully” is printed to indicate the successful division.
- If the user enters a non-integer value (e.g., a string) for the denominator, a ValueError occurs during the conversion.
- If any other unanticipated exception occurs (not a ValueError), the generic except block catches it.
- The except block is executed with the message “OOPS…..SOME EXCEPTION RAISED,” providing a generic response for any unhandled exceptions.
Output:
>>Handling exceptions without naming them
>>Enter the denominator: 5
>>Division performed successfully
>>Enter the denominator: abc
>>Only INTEGERS should be entered
>>Enter the denominator: 0
>>OOPS…..SOME EXCEPTION RAISED