Search code examples
pythonexceptionpydoc

Pydoc Uncaught Exception


I looked up sys in pydoc because a book I am reading recommended it to me, I came across last_type which was type of last uncaught exception, my question is what is an uncaught exception in pydoc/python and what is it used for?


Solution

  • An uncaught exception is just every exception which has not been handled by an except-handler within a try-except statement and hence causes your script to stop.

    If this happens the interpreter by default prints the type of the exception, an error message and a traceback.

    So if you, for example try to print(1/0), you'll get an exception with type ZeroDivisionError, an error message "division by zero" and the last steps through your code which led to the exception (traceback).

    print(1/0)
    Traceback (most recent call last):
      File "E:\Programme\Anaconda3\envs\py36\lib\site-
    packages\IPython\core\interactiveshell.py", line 2910, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-12-2fc232d1511a>", line 1, in <module>
        print(1/0)
    ZeroDivisionError: division by zero
    

    An uncaught exception lets you know that something went wrong. You then have to remove the error source (maybe you actually wanted to write print(1/10), or you have to catch and handle the exception, allowing your program to resume execution of code beneath the error source.

    try:
        1/0
    except ZeroDivisionError as err:  # error is caught here
        pass # e.g just do nothing
        # print(type(err).__name__, flush=True)  # or do something, like print
                                                 # error type
    
    print("will be printed because exception before was caught")