Try...except in Python
try...except in Python
The try...except block in Python is used for handling exceptions (runtime errors). It allows the program to continue executing even if an error occurs, rather than crashing.
Syntax:
try: # Code that might raise an exception # Try block where you write code that could potentially cause an errorexcept SomeException: # Code that runs if an exception occurs in the try block # Handles the exceptionelse: # Code that runs if no exception occurs in the try block # Optional block that executes if no error occurred in tryfinally: # Code that runs no matter what, whether an exception occurs or not # Optional block that always runs (useful for cleanup operations)1. Basic Example of try...except
try: x = 10 / 0 # This will raise a ZeroDivisionErrorexcept ZeroDivisionError: print("You can't divide by zero!")Explanation: The
tryblock contains code that may raise an error (in this case, division by zero). If the exception occurs, it is caught by theexceptblock and an appropriate message is printed.
2. Handling Multiple Exceptions
You can handle different types of exceptions by using multiple except blocks.
try: x = int(input("Enter a number: ")) result = 10 / xexcept ValueError: print("That was not a valid number!")except ZeroDivisionError: print("You can't divide by zero!")Explanation: The code first attempts to convert input to an integer and then divides 10 by the number. If the input is not a valid number, a
ValueErroris raised. If the user enters zero, aZeroDivisionErroris raised.
3. Catching All Exceptions
To catch all exceptions (which is not recommended for general use but useful for debugging), you can use the base Exception class.
try: x = 10 / 0 # This will raise a ZeroDivisionErrorexcept Exception as e: print(f"An error occurred: {e}")Explanation: The
Exceptionclass is the base class for all built-in exceptions in Python, and it will catch any type of error that occurs in thetryblock.
4. Using the else Block
The else block runs only if the code in the try block does not raise an exception.
try: x = 10 / 2 # This will execute without an errorexcept ZeroDivisionError: print("You can't divide by zero!")else: print("Division was successful!")Explanation: If no exception occurs in the
tryblock, theelseblock executes.
5. Using the finally Block
The finally block always executes, regardless of whether an exception occurred or not. It is often used for cleanup activities like closing files or releasing resources.
try: file = open("myfile.txt", "r") # Do something with the fileexcept FileNotFoundError: print("File not found!")finally: print("This block will always execute.") file.close() # Ensure the file is closed even if an error occursExplanation: In this example, the
finallyblock ensures that the file is closed whether or not an error occurs when trying to open the file.
6. Raising Exceptions Manually
You can also raise exceptions explicitly using the raise keyword.
try: age = int(input("Enter your age: ")) if age < 0: raise ValueError("Age cannot be negative!")except ValueError as e: print(e)Explanation: If the user enters a negative age, a
ValueErroris raised manually using theraisekeyword, and the exception is caught in theexceptblock.
7. Conclusion
The try...except block is a powerful tool in Python for handling errors gracefully. It allows the program to recover from runtime errors and continue executing. Here's a summary of its components:
try: Contains code that might raise an exception.except: Catches and handles exceptions raised in thetryblock.else: Executes if no exception occurs.finally: Always executes, regardless of whether an exception occurred or not.
By using try...except, you can make your Python programs more robust and less likely to crash due to unexpected errors.