Home » Data Science » Python » Python Try except

Newly Updated Posts

Python Try except

The try and except commands are used in Python to handle errors and exceptions. They let you to manage potential exceptions that may arise while your code is being executed, preventing your program from crashing.

The basic syntax for using try and except is as follows:

try:
    # code that might raise an exception
    # ...
except ExceptionType1:
    # code to handle the exception of type ExceptionType1
    # ...
except ExceptionType2:
    # code to handle the exception of type ExceptionType2
    # ...
else:
    # optional block executed if no exceptions were raised
    # ...
finally:
    # optional block of code that will be executed regardless of whether an exception occurred or not
    # ...

Here’s a breakdown of the different parts:

  • The try block contains the code that you want to execute, which might raise an exception.
  • If an exception of type ExceptionType1 occurs in the try block, the corresponding except block will be executed. You can have multiple except blocks to handle different types of exceptions.
  • The else block is optional and is executed if no exceptions were raised in the try block.
  • The finally block is also optional and is executed regardless of whether an exception occurred or not. It is typically used for cleanup tasks, such as closing files or releasing resources.

Here’s an example that demonstrates the usage of try and except:

try:
    x = int(input("Enter a number: "))
    result = 10 / x
    print("The result is:", result)
except ValueError:
    print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("No exceptions were raised.")
finally:
    print("This block always executes.")

In this example, if the user enters a non-numeric value, a ValueError exception will be raised, and the corresponding except block will handle it. If the user enters zero, a ZeroDivisionError exception will be raised. If the user enters a valid number, the code in the else block will be executed. Finally, the finally block will be executed regardless of the outcome.

By using try and except, you can gracefully handle exceptions and provide appropriate error messages or alternative behavior, improving the robustness of your code.