Account
Categories

Try and Except block


Definition:

When you write a program, and you use the try and except block, you write the code that may produce an error inside the try block,

and the message that explains the error is placed inside the except block. And when you run the program, the try block checks for the error.

If it finds the error, the except block runs the code and displays the message, and if it does not find the error, then the try block runs the code.

You can use this block inside functions, loops, and if-else blocks, etc.

Now you will clearly understand the try..except code logic with the help of this flowchart.

Start
  |
  v
Write code inside Try block
  |
  v
Run Try block
  |
  v
Is there an error?
  |
  |--- Yes ---> Run Except block ---> Display "error" ---> End
  |
  |--- No ----> Try block completes ---> End

Syntax:

try:
    # Code that may cause an error
except Exception as error:
    # Code to handle the error

Example:

try:
    result = 5 / 0
except Exception as error:
    print("error")

Output: