try Block

Try Block

What is a try Block?

The try block in Python is used for exception handling, it means that this block is tested for errors while the program is running. The code within a try block is executed statement by statement. If an error occurs, the rest of the code within the try block is skipped, and Python looks for an appropriate except block to manage the specific error that occurred.

Syntax of try Block

The try block has a very simple syntax. A Python try block is written as follows:

try:
    # Code that may cause an error

How to Use try Block

Here’s an example of how the try block can be used to anticipate and handle a ZeroDivisionError. In this case, the exception occurs when we try to divide a number by zero.

1try:
2    print(5/0)
3except ZeroDivisionError:
4    print("Sorry, you're dividing by zero. Please avoid that.")

In this code, Python encounters a ZeroDivisionError at line 2 during execution and immediately jumps to the except block. The except block defines the response to the error, which, in this case, is to print out a message.

Note

The try block always needs at least one except block to be useful. The except block is designed to catch and handle exceptions if any occur within the try block.

Multiple Statements in a try Block

You can include more than one statement in a try block. Here’s an example:

1try:
2    print(5/0)
3    print("This is a message.")
4except ZeroDivisionError:
5    print("Sorry, you're dividing by zero. Please avoid that.")

In this example, the print statement on line 3 within the try block is not executed. This is because Python skips the remainder of the try block after encountering an exception.

Did you know?

If you want some code to be executed regardless of whether or not an exception occurs, you can use the finally block.