Try statement in Python

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:

# 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:

An IO Error occurred.Details:

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


Copyright 2024 © pythontic.com