try statement in Python

In Python try statement encloses a block of code for which exception handling needs to be provided. The try block typically is followed by a set of except blocks and an optional finally block.

Keywords Updated 20 May 2019 1 min read

In Python, try is the keyword that marks a block of code for handling potenital exceptions. The try block is followed by one or more except blocks (i.e., exception handlers) and an optional finally block. The exception handling mechanism in Python is provided through the keywords try, except, finally and raise.

Example

python
# import the socket module

import socket

# Create a socket object

try:

    socketObject = socket.socket()

    # Establish connection to a http server(a non existing one)

    addressToConnect = "http://www.non-existing-example.com"

    socketObject.connect((addressToConnect, 80))

    print("Connected to specified host")

    # Request for a http page

    HTTPMessage = "GET / HTTP/1.1\r\nHost: localhost\r\n Connection: close\r\n\r\n"

    bytes       = str.encode(HTTPMessage)

    socketObject.sendall(bytes)

    # Receive the data

    while(True):

        data = socketObject.recv(1024)

        print(data)

        if(data==b''):

            print("Closing the connection")

            break

        socketObject.close()

except IOError as Ex:

    print("An IO Error occurred.Details:")

    print(Ex)

except:

    print(Ex)

Output

Output
An IO Error occurred.Details:

[Errno 8] nodename nor servname provided, or not known