Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ''except Exception as e'' mean in python? [closed]

The typical structure for exception handling is below:

try:
    pass
except Exception, e:
    raise
else:
    pass
finally:
    pass

May I know what does except Exception, e:orexcept Exception as e: mean? Typically I will use print (e) to print the error message but I am wondering what the program has done to generate the e.

If I were to construct it in another way (below), how would it be like?

except Exception:
    e = Exception.something

What should the method be to replace the something?

When the body of code under try gives no exception, the program will execute the code under else. But, what does finally do here?

like image 427
lxjhk Avatar asked Dec 17 '14 02:12

lxjhk


People also ask

What is except exception as e in Python?

User-Defined Exceptions This is useful when you need to display more specific information when an exception is caught. In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.

What does except exception mean in Python?

except is used to catch and handle the exception(s) that are encountered in the try clause. else lets you code sections that should run only when no exceptions are encountered in the try clause.

What's the difference between except exception E and except exception as e?

In contrast, the except Exception as e statement is a statement that defines an argument to the except statement. e in the latter statement is utilized to create an instance of the given Exception in the code and makes all of the attributes of the given Exception object accessible to the user.

Can I leave except block empty in Python?

Ignoring a specific exception by using pass in the except block is totally fine in Python. Using bare excepts (without specifying an exception type) however is not. Don't do it, unless it's for debugging or if you actually handle those exceptions in some way (logging, filtering and re-raising some of them, ...).


1 Answers

except Exception as e, or except Exception, e (Python 2.x only) means that it catches exceptions of type Exception, and in the except: block, the exception that was raised (the actual object, not the exception class) is bound to the variable e.

As for finally, it's a block that always gets executed, regardless of what happens, after the except block (if an exception is raised) but always before anything else that would jump out of the scope is triggered (e.g. return, continue or raise).

like image 190
Max Noel Avatar answered Oct 16 '22 10:10

Max Noel