Catch any error in Python

Viewed 57432

Is it possible to catch any error in Python? I don't care what the specific exceptions will be, because all of them will have the same fallback.

8 Answers

Quoting the bounty text:

I want to be able to capture ANY exception even weird ones like keyboard interrupt or even system exit (e.g. if my HPC manger throws an error) and get a handle to the exception object e, whatever it might be. I want to process e and custom print it or even send it by email

Look at the exception hierarchy, you need to catch BaseException:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception

This will capture KeyboardInterrupt, SystemExit, and GeneratorExit, which all inherit from BaseException but not from Exception, e.g.

try:
    raise SystemExit
except BaseException as e:
    print(e.with_traceback)

Not mentioning the type of exception you want to handle itself does the job.

try this:

    try:
       #code in which you expect an exception 
    except:
       #prints the exception occured

if you want to know the type of exception occurred:

    try:
       #code in which you expect an exception 
    except Exception as e:
       print(e)
       #for any exception to be catched

for detailed explanation go trough this https://www.tutorialspoint.com/python/python_exceptions.htm

# in python 3

# if you want the error
try:
    func()
except Exception as e:
    exceptionFunc(e)

# if you simply want to know an error occurs
try:
    func()
except:
    exceptionFunc()

# if you don't even wanna do anything
try:
    func()
except:
    pass

The following only worked for me (both in PY2 and PY3):

try:
  # (Anything that produces any kind of error)
except:
  ertype = sys.exc_info()[0]  # E.g. <class 'PermissionError'>
  description = sys.exc_info()[1]   # E.g. [Errno 13] Permission denied: ...
  # (Handle as needed ) 

Built-In Exceptions in Python

Built-In exception classes are divided into Base error classes from which the error classes are defined and Concrete error classes which define exceptions which you are more likely to see time to time.

The more detailed document about the buit-In exception can be found in [https://docs.python.org/3/library/exceptions.html]

Custom Exceptions

It is used to fit your specific application situation. For example, you can create your own exception as RecipeNotValidError as the recipe is not valid in your class for developing a cooking app.

Implementation


class RecipeNotValidError(Exception):    
    def __init__(self):       
        self.message = "Your recipe is not valid"        
        try:            
            raise RecipeNotValidError
        except RecipeNotValidError as e:            
            print(e.message)

These are custom exceptions that are not defined in the standard library. The steps you can follow to create custom classes are :

  1. Subclass the Exception class.
  2. Create a new Exception class of your choice.
  3. Write your code and use the try...except flow to capture and handle your custom exception.
Related