Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3 try-except all with error [duplicate]

Is it possible to do a try-except catch all that still shows the error without catching every possible exception? I have a case where exceptions will happen once a day every few days in a script running 24/7. I can't let the script die but they also don't matter since it retries regardless as long as I try except everything. So while I track down any last rare exceptions I want to log those to a file for future debugging.

example:

try:     print(555) except:     print("type error: "+ str(the_error)) 

Any way to replace the_error with a stack trace or something similar?

like image 390
Ryan Mills Avatar asked Nov 03 '17 20:11

Ryan Mills


People also ask

Can you use except twice in Python?

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

How do you catch all errors in Python?

Another way to catch all Python exceptions when it occurs during runtime is to use the raise keyword. It is a manual process wherein you can optionally pass values to the exception to clarify the reason why it was raised. if x <= 0: raise ValueError(“It is not a positive number!”)

Is try-except Pythonic?

A Try-Except statement is a code block that allows your program to take alternative actions in case an error occurs. Python will first attempt to execute the code in the try statement (code block 1). If no exception occurs, the except statement is skipped and the execution of the try statement is finished.

Is try-except faster than if?

Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code.


1 Answers

Yes you can catch all errors like so:

try:     print(555) except Exception as e:     print("type error: " + str(e)) 

For the stack trace I usually use the traceback module:

import traceback  try:     print(555) except Exception as e:     print("type error: " + str(e))     print(traceback.format_exc()) 
like image 152
Cyzanfar Avatar answered Sep 19 '22 12:09

Cyzanfar