Search code examples
pythonexceptionerror-handlingnestedraise

Python exception handling and raising


let's say I have the following 3 scripts:

script1.py
script2.py
script3.py

Lets say I get a traceback like this:

Traceback (most recent call last):
File "script1.py", line xyz, in ...
...
File "script2.py", line xyz, in ...
...
File "script3.py", line xyz, in ...
...
AttributeError: 'NoneType' object has no attribute 'CoolAttribute'

I have several different exceptions that occur in script3.py. Is there a way to handle ANY of these exceptions in line xyz in script1.py without handling the exceptions in script2.py? I just want to handle the exceptions that stem from script3.py in one line in script1.py.


Solution

  • One simple dirty way to do it is wrap you simple3.py with try except close and raise custom exception on any script3 exceptions.

    class BaseSimpleError(Exception):
        """dummy class for all Simple3 errors"""
    
    try:
        ...your simple3.py goes here...
    except Exception, e:
        raise BaseSimpleError()
    

    In script1 you should import BaseSimpleError and catch it when required.