Wednesday, February 26, 2020

Errors And Exceptions In Python

Errors And Exceptions In Python


Errors

The errors cannot be handled generally by programmers. Like, syntax errors, recursion error, memory out of bounds, etc. The errors can and should not be handled by the programmer, for example, we can not handle stack overflow or the memory out of bounds errors.

Exceptions  

A program can contain errors or exceptions, for example when the parser detects an incorrect statement(Syntax Error) the program cannot be executed. Few errors in a program are not syntax errors. They are detected during execution of the program only, such errors are known as exceptions. This type of error occurs whenever a syntactically correct program results in an error. The program terminates as soon as it encounters an error. Most exceptions aren't handled by programs but, it is possible to write programs in Python that can handle selected exceptions.

Syntax Error


#Syntax error
a=12
b='python'
print(a+b)

Output:

Traceback (most recent call last):
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 3, in <module>
    print(a+b)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Process finished with exit code 1

Identation Error

#identation error

for item in range(5):
print(item)

Output:
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 4    print(item)
        ^
IndentationError: expected an indented block

Process finished with exit code 1

Recursion Error

#recursion error
def rec():
    return rec()
rec()

Output:
Traceback (most recent call last):
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 4, in <module>
    rec()
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 3, in rec
    return rec()
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 3, in rec
    return rec()
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 3, in rec
    return rec()
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded

Process finished with exit code 1

Built-in Exceptions

Python provides an excellent exception handling mechanism to handle the exceptions and exception logic gracefully. Python provides a rich set of built-in exceptions. All Built-in Exceptions in Python are inherited from the BaseException type.

 

Exception Class

Event

IOError

Due to an input/output operation is unsuccessful.

ArithmeticError

Due to numeric calculations is unsuccessful.

Floating-pointError

Due to a floating-point calculation is unsuccessful.

ZeroDivisionError

Due to division or modulo by zero takes place for all numeric types.

AssertionError

Due to the assert, the statement is unsuccessful.

OverflowError

Due to the result of an arithmetic operation is too large to be represented.

ImportError

Due to the imported module is not found.

IndexError

Due to the index of a sequence is out of range.

KeyboardInterruptError

Due to the user interrupts program execution, generally by pressing (Ctrl+C).

IndentationError

Due to there is a wrong indentation.

SyntaxError

Raised by the parser when a syntax error is encountered.

KeyError

Due to the specified key is not found in the dictionary.

NameError

Due to an identifier is not found in the local or global namespace.

TypeError

Due to a function or operation is applied to an object of an incorrect type.

ValueError

Due to a function gets an argument of the correct type but of an improper value.

RuntimeError

Due to a generated error does not fall into any category.


There are four main components of exception handling

try

The block of code is expected to have the exception.

except

This block of code is executed if the exception occurs.

else

This block of code is executed if no exception occurred in the code.

finally

This block of code will be executed in all circumstances, whether there is an exception or not.

The common syntax for exception handling

try-except-else-finally
Exception handling


Handling  Common Exceptions

Arithmetic Error

There can be an arithmetic error like Zero Division Error, OverFlow, and Floating-point Error,

Zero Division Error

Zero Division Error occurs when a number is divided by zero.

#Zero Division Error
try:
    a=10
    b=0
    print(a/b)
except ZeroDivisionError:
    print("Zero division Error occured")
else:
    print('No Exception occured')

Output:
Zero division Error occured

Process finished with exit code 0

OverFlowError 

Overflow Error is raised when the result of the evaluation goes beyond the valid range.
#OverFlow Error
import math
try:
    print(math.exp(1000))
except OverflowError:
    print("Over Flow Error occured")
else:
    print('No Exception occured')


Output:

Over Flow Error occured

Assertion Error

The Assertion Error occurs when an Assert fails

#Assertion Error
try:
    a=10
    b='Python'
    assert a==b
except AssertionError:
    print("Assertion Error occured")
else:
    print('No Exception occured')
Output:
Assertion Error occured

ImortError

Import Error occurs when a non-existent module(unable to load) is tried to import.
#import Error
import nibabel
print([10,12,14])
Output:
Traceback (most recent call last):
  File "C:/Users/my/PycharmProjects/Facebook/venv/test.py", line 2, in <module>
    import nibabel
ModuleNotFoundError: No module named 'nibabel'

Lookup Errors

LookupError is the base class for the invalid key and index related errors.
Like IndexError and KeyError

IndexError

If the invalid index is accessed IndexError is raised.
#index Error
try:
    l=[10,12,14]
    print(l[3])
except IndexError:
    print('Wrong index')
else:
    print('No exception')
Output:
Wrong index

KeyError

If key is not available in dictionary but tried to access the KeyError is raised.
#Key Error
try:
    l={1:'Apple',2:'Ball',3:'Cat'}
    print(l[4])
except KeyError:
    print('KeyError occured')
else:
    print('No exception')

Output:
KeyError occured

MemoryError

MemoryError is raised when not enoough memory is available for the process to proceed further.

NameError

NameError is occured when a name whether it is global or local is not found.
#NameError
try:
    l={1:'Apple',2:'Ball',3:'Cat'}
    print(a) #a is not defined anywhere
except NameError:
    print('Name error')
else:
    print('No exception')

Output:
Name error
Disadvanatge of Python's Exception Handling is that the Python program with 
exception handling executes slower and the size of code also increases.