📜  python try except loop - Python(1)

📅  最后修改于: 2023-12-03 15:04:09.570000             🧑  作者: Mango

Python Try Except Loop

Python has a built-in error handling mechanism that allows you to handle exceptions (errors) gracefully instead of stopping your program altogether. This mechanism is known as try-except.

Try-Except block lets you catch errors that may occur during runtime and take corrective actions to prevent the program from crashing.

Syntax
try:
    # code to be executed here
except ExceptionType:
    # code to handle the exception
  • try block contains the code that may raise an exception
  • except block contains the code to handle the exception
  • ExceptionType specifies the type of exception to handle (optional)
Examples

Let's see some examples of Try-Except block in action:

Example 1: Catching Divide-by-Zero Error

In this example, we'll catch the ZeroDivisionError that may occur if we try to divide a number by zero:

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
    print("Result:", result)
except ZeroDivisionError:
    print("Cannot divide by zero!")

Output:

Enter a number: 10
Enter another number: 0
Cannot divide by zero!
Example 2: Catching Input Error

In this example, we'll catch the ValueError that may occur if we enter an invalid input:

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
    print("Result:", result)
except ValueError:
    print("Invalid input!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

Output:

Enter a number: 10
Enter another number: abc
Invalid input!
Example 3: Using Else Block

In this example, we'll use the else block to execute some code only if no exception occurs:

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

Output:

Enter a number: 10
Enter another number: 2
Result: 5.0
Execution complete.
Example 4: Using Loop

In this example, we'll use a loop to keep asking for input until the user enters valid input:

while True:
    try:
        num1 = int(input("Enter a number: "))
        num2 = int(input("Enter another number: "))
        result = num1 / num2
    except ValueError:
        print("Invalid input! Try again.")
    except ZeroDivisionError:
        print("Cannot divide by zero! Try again.")
    else:
        print("Result:", result)
        break
    finally:
        print("Attempt complete.")

Output:

Enter a number: 10
Enter another number: 0
Cannot divide by zero! Try again.
Attempt complete.
Enter a number: 10
Enter another number: abc
Invalid input! Try again.
Attempt complete.
Enter a number: 10
Enter another number: 2
Result: 5.0
Attempt complete.

In conclusion, Try-Except block is an essential tool in Python programming as it helps to prevent program crashing errors by handling exceptions gracefully. By following the examples shown above, you can implement Try-Except block into your code and better manage error handling in your programs.