Python Try Except Exception Handling

In this post, we’ll learn about Python Try Except and Exception Handling practices.
Try Except are two important blocks of exception handling these are helpful in preventing the unpredicted, unforeseen errors in the program.
They flexibly handle mistakes which help in identifying bugs easy.

Some examples of errors

>>> 1/0
#PYTHON OUPUT
Traceback (most recent call last):
File "", line 1, in 
ZeroDivisionError: division by zero

>>> x/5
#PYTHON OUPUT
Traceback (most recent call last):
File "", line 1, in 
NameError: name 'x' is not defined

ZeroDivisionError caused when a number is divided by zero.
NameError caused as the variable x was not initialized. You’ll learn more of them in the below examples.

Creating Try Except block

We start by specifying try block and inside it will run program code.
In except the block will print or log the exception occurred while testing the code.

Note: Exception is of different types you’ll learn those in this tutorial.

    try:
        a=10
        b='12'
        c=a+b
        print("Result {}".format(c))
    except:
        print("Exception has occured while adding two numbers")

    #PYTHON OUTPUT
    Exception has occured while adding two numbers

In the above scenario, we are testing the addition operation.
But you can observe that in try block we are preforming addition on a number and
another is a string so when we run code we will get error and
try block will pass the error to except block to handle it in a more graceful manner
only if the error has occurred else will skip that step.

We can also chain the except block multiple times

try:
    a=10
    b='12'
    c=a+b
    print("Result {}".format(c))
except NameError:
    print("Variable is not defined")
except ZeroDivisionError:
    print("Error while trying to divide by Zero")
except TypeError:
    print("Unsupported Operands.")  

#PYTHON OUTPUT
Unsupported Operands.

Handling more than one exceptions

try:
    a=21
    b=0
    c=a/b
    print(c)
except NameError as n:
    print("Variable is not defined \n message : {}".format(n))
except ZeroDivisionError as z:
    print("Error while trying to divide by Zero \n message : {}".format(z))
except TypeError:
    print("Unsupported Operands \n message : {}".format(z))  

#PYTHON OUTPUT
Error while trying to divide by Zero 
    message : division by zero

Insisted on calling except block one after another we can assign all the above exceptions
in a single block.

try:
    a=21
    b=0
    c=a/c
    print(c)
except (NameError, ZeroDivisionError, TypeError):
    print('Error has occured.')

#PYTHON OUTPUT
Error has occured.

Try except and finally

Finally is an optional statement in the try-except block. This executes every time whenever the try-except statement
is performed even if an error has occurred.

try:
    a=21
    b=0
    c=a/b
    print(c)
except:
    print("Exception has occured.")
finally:
    print("Finally block is executed every time try...except block is executed.")

#PYTHON OUTPUT
Exception has occured.
Finally block is executed every time try...except block is executed.

Raising Exceptions

raise are exception handling statements? They are helpful for specified cases where programmer intentionally raises and exception message.

Raising exception using the raise statement

In this example, we’ll raise error without try-except statement.

a = None
if a != None:
    print("exists")
else:
    raise Exception("Variable is not defined.")

#PYTHON OUTPUT
Traceback (most recent call last):
File "main.py", line 6, in 
    raise Exception("Variable is not defined.")
Exception: Variable is not defined.

As you can see in the above example we are verifying the value in a variable. If the value is `None` then we manually raise
exception error. This is helpful in debugging of code.

Top Python Posts