Understanding Exception in Python

In this class, we discuss Understanding Exception in Python.

For Complete YouTube Video: Click Here

Understanding Exception

The reader should have prior knowledge of object-oriented concepts. Click here.

Take an example and understand the idea of exception.

if x<n
   print("greater")
else:
   print("lesser")

In the above example, if the condition is True. Print greater. Otherwise, print lesser.

The problem with the above code. The if statement is not having a colon.

The missing colon is detected during compilation. Because it is a syntax error.

Example to understand exception.

a=int(input("enter first number"))
b=int(input("enter second number"))
c=a/b
print(c)

Output:
ZeroDivisionError: division by zero

In the above example, we had statement a/b.

The values of a and b are taken from the user during execution.

Suppose the value of b is given zero. Divided by zero is not possible.

The problems that are occurred during the execution of the program we call exception.

The problem mentioned above is one example.

There are many other exceptions. Some are given below.

File not found exception. If we want to access a file, we give the file name.

During execution, It will check the file available or not.

Index error. We have given an index of a list to access the element in the list.

If the index position is not available in the list. We can not access the element.

This index position is identified during the execution of the program.

Example:

lis=[1,2,3]

print(lis[5])

Whenever python encounters an exception, it will stop executing the program and display a message.

The message python display is shown in the example given below.

In the above program, the message displayed is zero division error.

Note: Point to understand. Every exception has its name.

This exception naming will help the programmer to debug the code easily.

Whenever a programmer sees the exception name. he can quickly identify the mistake in the code.

Exception Handling:

The python interpreter stops executing the program when it sees an exception.

Exception handling means do not stop executing the program. Let the programmer handle the situation.

Providing this facility, we called exception handling. Exception handling is explained in our next classes.

List of exceptions:

print(dir(locals()[‘__builtins__’]))

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

The above code will display the list of exceptions available in python.

There are so many exceptions available.

For example, when we are developing an application. We get an aborted connection error if the network fails.

When we are writing code related to operating systems, we get memory exceptions.

In our course, we discuss general programming exceptions in the following classes.