w3resource

Exploring Python's Try Block for exception handling

How does the try block work in handling exceptions in Python?

The "try" block in Python encloses a section of code where exceptions might occur. It defines a scope within which the interpreter monitors for exceptions.

Here is how it works:

  • The code that could raise an exception is placed inside the try block.
  • When an exception occurs in the try block, Python immediately stops execution of the "try" block code.
  • It will then jump to the appropriate "except" block to handle that exception.
  • If no exception occurs, the "try" block will execute completely.

For example:

Code:

try:
    n = int(input("Input a number: "))
    result = 100 / n
    print("Result:", result)
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input, please input a number.")

Output:

Input a number: abcd
Invalid input, please input a number.
Input a number: 12
Result: 8.333333333333334
Input a number: 0
Cannot divide by zero!

In the example above:

  • If the user inputs 0, a "ZeroDivisionError" exception is raised, and the program jumps to the corresponding "except" "ZeroDivisionError" block.
  • If the user inputs a non-numeric input, a "ValueError" exception is raised, and the program jumps to the corresponding "except" "ValueError block".


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/how-does-the-try-block-work-in-handling-exceptions-in-python.php