TypeError – invalid operation on data type

This code defines two variables a and b and assigns values 5 and 'a' to them respectively.

The code then tries to evaluate the expression a + b, where a is an integer and b is a string. The result of such an operation would raise a TypeError, as you cannot add an integer and a string together in Python.

To handle such exceptions, the code uses a try-except block to catch the error. In case a TypeError is raised, the code inside the except block will be executed.

The code inside the except block first prints the type of the exception object, which is TypeError, using the type function. Then, it prints the error message contained in the exception object e using print(e). Finally, it prints a customized error message “customized error message”.

The try-except block allows the code to continue executing even in the presence of errors, without crashing the program. It provides a way to handle exceptions and provides a more user-friendly output.

a, b = 5, 'a'

try:
    result = a + b
except TypeError as e:
    print(type(e))
    print(e)
    print("customized error message")
Output
<class 'TypeError'>
unsupported operand type(s) for +: 'int' and 'str'
customized error message