The Python language actually can handle exceptions (Perl and C do not where as Java or C++ do), what this means is that if a error happens in a program (for example database or file connection issue) you can write code that will handle this error so that the program does not crash, you also might want to perform some tidy up before the program continues. I will have a more advanced example later but below is the basic concept of exceptions
Try to use exception in code that may fial due to external issues, database connections, file i/o, networking, etc.
try-except block | try: # do stuff except Exception: # handle exceptions |
Python uses object-oriented, an exception is a OOP object, it is automatically generated by Python functions with a raise statement. When an exception is raised the program will then look for a handler to handle the issue, if the handler is found the code is executed in that handler, if no handler is found then the program aborts.
Python can handle many types of exceptions, the baseException type contains all exceptions, you can even define your own. Because the exception set is hierarchical to can use higher exception type to capture many types of exceptions, so using the Exception type would be a good idea.
Built-in exception types | BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- 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 +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning |
Exceptions are raised by many of Pythons built-in functions, but you can raise your own if something goes wrong
Raise exception | raise exception(args) |
Catching and Handling Exceptions
You can handle multiple exceptions each with its handler code, the below code is executed in the following way
Catch and handle exceptions | try: body except exception_type1 as var1: # handles a specific type of exception exception_code1 except exception_type2 as var2: # handles a specific type of exception exception_code2 except: # catch-all handler default_exception_code else: else_body # only executed if try block is successful finally: finally_body # only executed after try, except and else blocks have executed, its always executed |
You can easy define your own exceptions, you create a class that inherits from the Exception class
Defining your own custom exception | class MyError(Exception): pass try: raise MyError("Some information about what went wrong") except MyError as error: print("Situation:", error) |
assert is a specialized form of a raise statement, the AssertError exception with the optional argument is raised if the expression evaluates to False and the system variable __debug__ is True. Assert can be used for debugging programs, code will be obmitted if the __debug__ statement is set to False.
Assert statement | x = (1, 2, 3) assert len(x) > 5, "len(x) not > 5" Note: an assertion exception will be throw with the message |