Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python handling specific error codes?

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.

like image 753
AustinM Avatar asked Mar 01 '11 22:03

AustinM


People also ask

How does Python handle specific errors?

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.

How can you catch a specific type of exception in Python?

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.

How do I print a specific error in Python?

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.

How do you catch error messages in Python?

message (at least in Python 2.7. 12). If you want to capture the error message, use str(e) , as in the other answers.


2 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.

like image 69
Utku Zihnioglu Avatar answered Sep 29 '22 03:09

Utku Zihnioglu


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.

like image 39
jchl Avatar answered Sep 29 '22 02:09

jchl