Python Exception

 

Python exception handling example

Fast answer

Here's a simple example of exception handling in Python using try, except, else, and finally:

try:
    num = int(input("Enter a number: "))
    result = 10 / num

except ValueError:
    print("Invalid input! Please enter a valid integer.")

except ZeroDivisionError:
    print("You cannot divide by zero.")

else:
    print("Result:", result)

finally:
    print("Execution completed.")

How it works

  • try: Contains code that might raise an exception.

  • except: Handles specific exceptions if they occur.

  • else: Runs only if no exception occurs.

  • finally: Always runs, regardless of whether an exception occurred.

Example Output 1 (Valid Input)

Enter a number: 2
Result: 5.0
Execution completed.

Example Output 2 (Division by Zero)

Enter a number: 0
You cannot divide by zero.
Execution completed.

Example Output 3 (Invalid Input)

Enter a number: abc
Invalid input! Please enter a valid integer.
Execution completed.

You can also catch multiple exceptions together:

try:
    value = int(input("Enter a number: "))
    print(100 / value)
except (ValueError, ZeroDivisionError) as e:
    print("An error occurred:", e)

This is useful when you want to handle several exception types in the same way.

Comments