Home

Errors and Exception

Error:

Errors are the problems in a program due to which the program will stop the execution.

Some Common Errors

  1. Syntax Errors
  2. Run-time Errors
  3. Logical Errors
  4. Latent Errors

IN [10]

# list of Errors and exceptions
for i in dir(__builtins__) + dir(__builtin__):
    if "Error" in i:
        print(i)

stdout

ArithmeticError
AssertionError
AttributeError
BlockingIOError
BrokenPipeError
BufferError
ChildProcessError
ConnectionAbortedError
ConnectionError
ConnectionRefusedError
ConnectionResetError
EOFError
EnvironmentError
FileExistsError
FileNotFoundError
FloatingPointError
IOError
ImportError
IndentationError
IndexError
InterruptedError
IsADirectoryError
KeyError
LookupError
MemoryError
ModuleNotFoundError
NameError
NotADirectoryError
NotImplementedError
OSError
OverflowError
PermissionError
ProcessLookupError
RecursionError
ReferenceError
RuntimeError
SyntaxError
SystemError
TabError
TimeoutError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
ValueError
WindowsError
ZeroDivisionError
ArithmeticError
AssertionError
AttributeError
BlockingIOError
BrokenPipeError
BufferError
ChildProcessError
ConnectionAbortedError
ConnectionError
ConnectionRefusedError
ConnectionResetError
EOFError
EnvironmentError
FileExistsError
FileNotFoundError
FloatingPointError
IOError
ImportError
IndentationError
IndexError
InterruptedError
IsADirectoryError
KeyError
LookupError
MemoryError
ModuleNotFoundError
NameError
NotADirectoryError
NotImplementedError
OSError
OverflowError
PermissionError
ProcessLookupError
RecursionError
ReferenceError
RuntimeError
SyntaxError
SystemError
TabError
TimeoutError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
ValueError
WindowsError
ZeroDivisionError

Exception:

Exceptions are raised when the some internal events occur which changes the normal flow of the program.

IN [9]

# list of Errors and exceptions
for i in dir(__builtins__) + dir(__builtin__):
    if "Exception" in i:
        print(i)

stdout

BaseException
Exception
BaseException
Exception

Traceback

The script used below is present here

IN [11]

def a():
    print("In a")
    b()
    print("Back in a")

def b():
    print("In b")
    return 42/0

a() 

stdout

In a
In b

Error

In a

In b


Traceback (most recent call last):

  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 10, in <module>

    a() 

  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 3, in a

    b()

  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 8, in b

    return 42/0

ZeroDivisionError: division by zero

Exception Handling:

Marking the error-prone zone and controlling what happens when an error / exception is raised is Exception Handling.

In python, Exception Handling can be done using the following:

  1. try block
  2. except block
  3. else block
  4. finally block

Syntax:

try:
    # Statements - Critical or Error Prone statements
except ErrorOrExceptionType:
    # Statements - What to do to handle errors
else:
    # Statements - What to do when error is not encountered
finally:
    # Statements - What to do at the end of Exception Handling

1. try block:

The critical operation that might not work as indented or may malfunction is enclosed in the try block. If the statement(s) raise any Error, the execution proceeding in the try block is terminated and moved to except block

try:
    # Statement(s) that may cause Errors

2. except block

The except block accepts the error/exception call and works as intended. The except block is used to filter the error that is anticipated.

except ErrorOrException:

The proper way of defining the except block is as above.
Though leaving out the Error name part works fine, it may cause a lot of confusion in many cases and is not recommended

except: # Not recommended for use

IN [2]

# Example
try:
    n = input()
    print(n / 10)
except TypeError:
    print("Error occurred")

stdin

 123

stdout

Error occurred

IN [3]

# Example - not recommended
try:
    n = input()
    print(n / 10)
except: # Don't do it this way
    print("Error occurred")

stdin

 159

stdout

Error occurred

3. else block

If there is no error in the code inside try block, the except block is skipped and the else block is executed.

else:
    # Statement(s) to run when no error is caused

IN [6]

# Example
try:
    n = int(input())
    print(10 / n)
except ZeroDivisionError: # Catch when there is division by zero (0)
    print("Error occurred")
else:
    print("Safe")

stdin

 10

stdout

1.0
Safe

4. finally block

This block is executed at all cases, whether or not an error is encountered inside the try block

finally:
    # Statement(s)

IN [1]

# Example
try:
    n = int(input())
    print(10 / n)
except ZeroDivisionError: # Catch when there is division by zero (0)
    print("Error occurred")
else:
    print("Safe")
finally:
    print("End of Program")

stdin

 0

stdout

Error occurred
End of Program

as keyword in except

Almost any case of exceptions returns a message about the cause of the error. The above defined method does not get the message for use.

Using as keyword, the error message can stored in a variable for use inside the except block.

except ErrorOrException as err:
    # Statement(s)

IN [2]

# Example
try:
    n = int(input())
    print(10 / n)
except ZeroDivisionError as e: # Catch when there is division by zero (0)
    print("Error occurred -", e) 
    # The message 'division by zero' is stored in e for use in the except block
else:
    print("Safe")
finally:
    print("End of Program")

stdin

 0

stdout

Error occurred - division by zero
End of Program

Intentionally Raising an Exception:

Python allows you to intentionally raise an exceptio at some cases using raise keyword.

Syntax:

raise ExceptionName("Message")

It is important to note that the exception following the raise keyword should either be an instance of a built-in exception or a class inheriting the same (Custom Exception).

IN [5]

# Example - Kelvin to Celsius Conversion
t = int(input("Enter temperature in Kelvin"))
if t < 0:
    raise ValueError("The minimum temperature in Kelvin is absolute zero (0)")
else:
    print(t - 273.15)

stdin

Enter temperature in Kelvin -1

Error

Enter temperature in Kelvin
Traceback (most recent call last):

  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 2, in <module>

    t = int(input("Enter temperature in Kelvin"))

ValueError: invalid literal for int() with base 10: 'Enter temperature in Kelvin -1'

Assertion statement:

An assertion is a sanity-check that you can turn on or turn off for testing your program.

The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression or condition is tested, and if the result comes up false, an exception is raised.

assert Statement:

When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.

assert expression, "Error message"

The assert statement is usually enclosed by a try block and the exception is handled. In some cases to terminate the execution, they may not be used.

IN [7]

# Example - Kelvin to Celsius Conversion
t = int(input("Enter temperature in Kelvin"))
try:
    assert t > 0, "The minimum temperature in Kelvin is absolute zero (0)"
except AssertionError as err:
    print(err)
else:
    print(t - 273.15)

stdin

Enter temperature in Kelvin -1

stdout

The minimum temperature in Kelvin is absolute zero (0)

Creating custom Errors/Exception from built-ins:

Python has numerous built-in exceptions that force your program to output an error when something in the program goes wrong.

However, sometimes you may need to create your own custom exceptions that serve your purpose.

In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.

class My_exception(Exception):
    pass

To know more about classes, visit Object Oriented Programming

IN [8]

class My_exception(Exception):
    pass

n = int(input())
if n > 100:
    raise My_exception("Number is large")
else:
    print(2 * n)

stdin

 101

Error


Traceback (most recent call last):

  File "D:\Programming\Python\Jupyter Notebooks\Python_Programming_Notes\temp.py", line 6, in <module>

    raise My_exception("Number is large")

__main__.My_exception: Number is large