Curriculum
Exception handling is a way to deal with errors that may occur in a Python program at runtime. It allows you to gracefully handle errors instead of crashing the program, and to take appropriate action based on the type of error that occurred.
In Python, exceptions are objects that represent errors or exceptional conditions that occur during the execution of a program. Exceptions are raised when an error occurs, and they can be caught and handled using a try
–except
block.
Here’s an example of how to use exception handling in Python:
try: x = int(input("Enter a number: ")) y = int(input("Enter another number: ")) result = x / y print("Result:", result) except ValueError: print("Invalid input: please enter a number.") except ZeroDivisionError: print("Cannot divide by zero.") except Exception as e: print("An error occurred:", e) finally: print("Done.")
In this example, we ask the user to enter two numbers and then divide them. We use a try
–except
block to catch and handle any exceptions that might occur during the execution of the program.
In the try
block, we convert the user input to integers, divide them, and print the result.
If a ValueError
exception is raised, the except
block for that exception will be executed and a message will be printed to the console.
If a ZeroDivisionError
exception is raised, the except
block for that exception will be executed and a message will be printed to the console.
If any other exception is raised, the except
block for the Exception
base class will be executed, and a message that includes the error message will be printed to the console.
The finally
block is always executed, regardless of whether an exception was raised or not.
Here are some examples of the output that might be produced by the program:
Example 1:
Enter a number: 10 Enter another number: 5 Result: 2.0 Done.
Example 2:
Enter a number: 10 Enter another number: 0 Cannot divide by zero. Done.
Example 3:
Enter a number: foo Invalid input: please enter a number. Done.
In summary, exception handling in Python allows you to gracefully handle errors that might occur during the execution of a program. You can catch and handle specific types of exceptions using try
–except
blocks, and take appropriate action based on the type of error that occurred.