Geek Slack

Introduction to Python
    About Lesson



    Python Try Except


    Python Try Except

    The tryexcept statement is used in Python to handle exceptions. It allows you to gracefully handle errors that may occur during the execution of your code.

    1. Basic Syntax

    The basic syntax of the tryexcept statement is as follows:

    try:
        # code that may raise an exception
    except ExceptionType:
        # code to handle the exception

    2. Handling Specific Exceptions

    You can specify the type of exception to catch using the except clause.

    Example:

    try:
        num = 10 / 0
    except ZeroDivisionError:
        print("Cannot divide by zero!")

    3. Handling Multiple Exceptions

    You can handle multiple exceptions by providing multiple except clauses or using a tuple of exception types.

    Example:

    try:
        num = int(input("Enter a number: "))
        result = 10 / num
    except ValueError:
        print("Invalid input!")
    except ZeroDivisionError:
        print("Cannot divide by zero!")

    4. Handling Any Exception

    You can catch any exception using the generic except clause without specifying the exception type.

    Example:

    try:
        # code that may raise an exception
    except:
        # code to handle any exception

    5. Using else and finally

    The else block is executed if no exceptions occur in the try block, while the finally block is always executed, regardless of whether an exception occurs or not.

    Example:

    try:
        num = int(input("Enter a number: "))
        result = 10 / num
    except ValueError:
        print("Invalid input!")
    except ZeroDivisionError:
        print("Cannot divide by zero!")
    else:
        print("Result:", result)
    finally:
        print("Execution complete!")

    Conclusion

    The tryexcept statement is a powerful tool for handling exceptions in Python, allowing you to gracefully handle errors and prevent your program from crashing unexpectedly.