Python Exceptions

Table of Contents

What are exceptions?

Exception can be any condition in a program resulting to the disruption in the flow of the program.
Whenever an exception occurs the program halts the execution and thus further code is not executed. Thus exception is that error which python script is unable to tackle with.
Python has many built-in exceptions which forces your program to output an error when something in it goes wrong.

Common Built-in Exceptions

ZeroDivisionError: Occurs when a number is divided by zero.
NameError:: It occurs when a name is not found. It may be local or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when end of the file is reached and yet operations are being performed.

Why use exceptions?

When exception occurs you can jump to an exception handler in a single step, abandoning all function calls begun since the exception handler was entered.
Codes in the exception handler can then respond to the raised exception.

Catching exceptions

Sometimes it is needed to remain active even after internal errors.
If you don’t want the default exception behavior, use try statement to catch exceptions yourself.
You can decide the behavior your program when it catches an exception.

Let's look at this example. Our function getdiv, gives a result after dividing ‘a’ with ‘b’. In ths case If we will pass the value of ‘b’ to be ‘0’, it will give ZeroDivisionError.

def getdiv(a,b):
    return a/b

getdiv(3,0)
Traceback (most recent call last):
….
ZeroDivisionError: division by zero

If no exception occurs, the code within the try clause will be executed statement by statement.
If an exception occurs , the rest of the try block will be skipped and the except clause will be executed.
In case of ZeroDivisionError the output will be, what we have given in the except block

def getdiv(a,b):
    try:
        return a/b
    except ZeroDivisionError:
        print("Denominator cannot be zero !")
        print("Please provide a valid input !")

getdiv(3,0)
Denominator cannot be zero!
Please provide a valid input!

Raising exceptions

You can explicitly throw an exception in Python using keyword “raise”.
It will cause an exception to occur and thus execution control will stop in case it is not handled.
We can also optionally pass in value to the exception.
Example:

def checknum(a):
    if a < 0:
        raise ValueError("Only positive integers are allowed")

    if a % 2 == 0:
        print("This an even number")
    else:
        print("This a odd number")

num = int(input("Enter a number: "))
checknum(num)

For negative number as input, the output will be

Enter a number: -2

ValueError: Only positive integers are allowed

User defined exceptions

User-defined exceptions are coded with classes, which inherit from a built-in exception class, usually the class named Exception.
Example:

class MyError(Exception):
    def __init__(self, val):
        self.val = val

    def __str__(self):
        return repr(self.val)

try:
    raise MyError(2300)
except MyError as e:
    print("Received error:{}".format(e.val))
Received error:2300

Cleanup actions

The try statement has another optional clause "finally", which is intended to define clean-up actions that must be executed under all circumstances.

try:
     raise KeyboardInterrupt
finally:
     print('Goodbye, world!')

Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last): File "<stdin>", line 2, in <module>

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
When an exception has occurred in the try clause and has not been handled by an except clause, it is re-raised after the finally clause has been executed.
The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.

Click any Link
to navigate to certain page easily
Write a line to us
Your Email
Title
Description