Exceptions#
Exceptions are a mechanism that the Python interpreter uses to identify errors in the code and notify the user
Exceptions are themselves defined as classes in Python
Ex: on encountering faulty syntax, the Python interpreter raises an exception of type
SyntaxError
a = 'string"
  Cell In[1], line 1
    a = 'string"
        ^
SyntaxError: unterminated string literal (detected at line 1)
Output of an exception includes:
Location info
Exception type and description
print(1 + '1')
Syntex errors are checked for before other kind of errors
The program is halted with an exception as soon as an error is encountered; rest of the code is ignored
Built-in Exceptions#
Exception- base class from which all other exception types are derivedSyntaxErrorIndentationError
ArithmeticError- math errorsOverflowError- occurs when a number is too large to store in afloatdatatypeZeroDivisionError- occurs when the 2nd argument of division or modulo operation is 0
NameError- variable name not found in any scopeTypeError- use of unsupported data types with an operatorLookupError- errors with sequences or dictionariesIndexError- invalid index is usedKeyError- invalid key is used
ImportError- occurs when an object is not defined in a moduleModuleNotFoundError- module to be imported cannot be found
…
Raising Exceptions#
Programmers can choose to
raisean exception to halt the programEither built-in or user-defined derived exceptions can be used
def UpperCase(strInp):
    if not isinstance(strInp, str):
        raise TypeError("Expecting a str object")
    return strInp.upper()
UpperCase('Abc')
UpperCase(12)
Code that adds numbers
Should check if each input is of a numeric type
def add(*args):
    s = 0
    for i in args:
        if not isinstance(i, (int, float, complex, bool)):
            raise TypeError("One of the inputs is not a number!")
        
        s += i
    return s
add(3, 2j)
add(1, [2])
Exception Handling#
Python provides the
try-exceptstatement to enable programmers to handle exceptions
A simple program with no exception handling:
i = int(input("Enter an integer: "))
print(f"Entered integer is {i}")
This will halt with a
ValueErrorif the input provided is not an integer
With exception handling:
try:
    i = int(input("Enter an integer: "))
except:
    print("Invalid input.")
else:
    print(f"Entered integer is {i}")