0

I usually use try-except blocks when I eg need input data from the user or try to start a thread. But is there some rule of thumb telling when one should definitely use a try-except block? As technically speaking nothing prohibits you of doing something as "clever" as:

try:
    print("Hello world")
except:
    print("Bye bye world")

Should I implement a try-except block whenever I for example feel like one of the following errors could arise?

$ python -m pydoc builtins


BaseException
    Exception
        ArithmeticError
            FloatingPointError
            OverflowError
            ZeroDivisionError
        AssertionError
        AttributeError
        BufferError
        EOFError
        ImportError
            ModuleNotFoundError
        LookupError
            IndexError
            KeyError
        MemoryError
        NameError
            UnboundLocalError
        OSError
            BlockingIOError
            ChildProcessError
            ConnectionError
                BrokenPipeError
                ConnectionAbortedError
                ConnectionRefusedError
                ConnectionResetError
            FileExistsError
            FileNotFoundError
            InterruptedError
            IsADirectoryError
            NotADirectoryError
            PermissionError
            ProcessLookupError
            TimeoutError
        ReferenceError
        RuntimeError
            NotImplementedError
            RecursionError
        StopAsyncIteration
        StopIteration
        SyntaxError
            IndentationError
                TabError
        SystemError
        TypeError
        ValueError
            UnicodeError
                UnicodeDecodeError
                UnicodeEncodeError
                UnicodeTranslateError
        Warning
            BytesWarning
            DeprecationWarning
            FutureWarning
            ImportWarning
            PendingDeprecationWarning
            ResourceWarning
            RuntimeWarning
            SyntaxWarning
            UnicodeWarning
            UserWarning
    GeneratorExit
    KeyboardInterrupt
    SystemExit
Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
  • ... and when you want them handled. But pls not with a blank `except`, specify what you error you intend to catch. – user2390182 Jan 11 '18 at 06:11
  • This is a very general question about [exception handling](https://en.wikipedia.org/wiki/Exception_handling) / error handling, too broad for this Q&A format. You should probably start by reading up on that topic. Then ask about specific cases when you take it into practice. – Jean-François Corbett Jan 11 '18 at 08:58

2 Answers2

3

It really should only be used when there are errors that might happen in a program that you want to handle a certain way. There might be errors you know could potentially happen, such as a memory error, but unless you want your program to react a certain way, you shouldn't use a try-except block.

For a smooth user experience, it might also be good to catch certain exceptions that are out of your control (like a Connection Error) so that you can tell your user what happened and they can try to remedy it.

TheBrownCoder
  • 1,186
  • 1
  • 10
  • 18
2

Exceptions are raised when called code encounters a problem that it cannot solve itself. For example when arguments are invalid, or when resources it attempts to access are not responding properly. Exceptions are generally meant to be exceptional and while they may occur when performing things, the normal control flow would be without exceptions.

You should catch exceptions, whenever called code could potentially raise an exception which you can recover from. That part is very important: There is no use catching an exception when you cannot work around that failure. Only catch exceptions that you expect to be raised.

That may seem counter intuitive after I having said that exceptions are exceptional, so expecting them seems weird. But the point is that code could raise any exception. For example, there are a lot of different external factors that could cause perfectly working code to suddenly raise an exception that it would usually never do. So you don’t just catch any exception. Instead you catch those exceptions explicitly that you expect to be eventually raised from the code and that you can work with without affecting your overall program.

I go into a lot more detail about this in my answer to another question: Why is “except: pass” a bad programming practice?

So basically, catch a specific exception when the code you are calling could raise that one and you could recover from it. Asking the user for input and want to parse this? Catch the exception from the parser and ask the user to correct it. Performing a network request to some API? Catch a network exception and maybe retry it. Writing a library for consuming an API that then performs a network request? Do not catch the network exception but let the consumer of your code decide how to recover from it.

Also, if you don’t know what exceptions code could raise, check the documentation. Usually the relevant exceptions are documented. There’s always a possibility that some exceptions may occur outside of the control of the called code, e.g. MemoryError, but those are usually neither to be expected nor really recoverable anyway, so you shouldn’t really check for those.

poke
  • 369,085
  • 72
  • 557
  • 602