Try Block in Python


In Python, the try block is used for exception handling. It allows you to test a block of code for errors, and if an error occurs, the program can handle it gracefully using an associated except block. This helps prevent your program from crashing unexpectedly and provides a way to deal with runtime errors.

Basic Syntax of try and except:

  • try:

  •     # Code that may raise an exception

  • except SomeException as e:

  •     # Code to handle the exception

  •     print("An error occurred:", e)


  • try: Contains the code that might throw an exception.

  • except: Catches and handles the exception if it occurs.

Example 1: Simple Try-Except

  • try:

  •     x = 5 / 0  # Division by zero error

  • except ZeroDivisionError as e:

  •     print("Error: Cannot divide by zero")


Output:

  • Error: Cannot divide by zero


In this example, the division by zero would raise a ZeroDivisionError. The except block catches the exception and prints the custom message.

Example 2: Catching Multiple Exceptions

You can handle different types of exceptions using multiple except blocks. Each except block will handle a different error type.

  • try:

  •     x = int(input("Enter a number: "))

  •     result = 10 / x

  • except ZeroDivisionError:

  •     print("Error: Cannot divide by zero.")

  • except ValueError:

  •     print("Error: Invalid input, please enter a number.")


Example 1: If you input 0, the program will print "Error: Cannot divide by zero." Example 2: If you input a non-numeric value (like "abc"), the program will print "Error: Invalid input, please enter a number."

Example 3: else and finally with try

You can also use the else and finally blocks along with try and except:

  • else: If no exception is raised in the try block, the else block will run.

  • finally: This block will always run, no matter if an exception occurs or not. It's often used for cleanup actions, like closing files or releasing resources.

  • try:

  •     x = 10 / 2

  • except ZeroDivisionError:

  •     print("Error: Division by zero")

  • else:

  •     print("Division successful!")

  • finally:

  •     print("This block always runs.")


Output:

  • Division successful!

  • This block always runs.


In this example:

  • The try block runs successfully without an exception, so the else block is executed.

  • The finally block always runs, regardless of whether an exception occurred or not.

Example 4: Raising Exceptions Manually

You can also raise exceptions manually using the raise keyword:

  • try:

  •     x = -1

  •     if x < 0:

  •         raise ValueError("Negative value is not allowed")

  • except ValueError as e:

  •     print(e)


Output:

  • Negative value is not allowed


In this case, the raise statement is used to manually raise a ValueError when x is negative.

Conclusion

The try block is a powerful feature in Python to handle runtime errors. By using it with except, else, and finally, you can handle errors gracefully, ensure proper cleanup, and make your programs more robust.

Let me know if you want to see more examples or if you have any questions! 😊


Post a Comment

0 Comments