Hey I'm wondering how to handle specific error codes. For example, [Errno 111] Connection refused
I want to catch this specific error in the socket module and print something.
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.
Try and Except Statement – Catching all Exceptions Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.
message (at least in Python 2.7. 12). If you want to capture the error message, use str(e) , as in the other answers.
If you want to get the error code, this seems to do the trick;
import errno try: socket_connection() except socket.error as error: if error.errno == errno.ECONNREFUSED: print(os.strerror(error.errno)) else: raise
You can look up errno
error codes.
On Unix platforms, at least, you can do the following.
import socket, errno try: # Do something... except socket.error as e: if e.errno == errno.ECONNREFUSED: # Handle the exception... else: raise
Before Python 2.6, use e.args[ 0 ]
instead of e.errno
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With