Exception Handling

An exception or error, means that the program will crash at some point. To prevent this, we use Exception Handling techniques, and try to find out where the error or exception occured.

Lets start with a basic program. What if we try to divide a number by 0?

def divideByZero(number):
    return 10/number

print(divideByZero(2))
print(divideByZero(0))

Here, we have defined a function that inputs a number, and divides 10 by that number.

The output would be:

5.0
Traceback (most recent call last):
  File "python.py", line 5, in <module>
    print(divideByZero(0))
  File "python.py", line 2, in divideByZero
    return 10 / number
ZeroDivisionError: division by zero

A ZeroDivisionError happens whenever we try to divide a number by zero. From the line number given in the error message, you know that the return statement in divideByZero() is causing an error.

Errors can be handled with try and except statements. The code that could potentially have an error is put in a try clause. The program execution moves to the start of a following except clause if an error happens.

You can put the previous code in a try clause and have an except clause contain code to handle what happens when this error occurs.

Let's put it into code now:

def divideByZero(number):
    try:
        return 10/number
    except ZeroDivisionError:
        print('Invalid Argument')

print(divideByZero(2))
print(divideByZero(0))

When code in a try clause causes an error, the program execution immediately moves to the code in the except clause. After running that code, the execution continues as normal.

The output will be:

5.0
Error: Invalid Argument

results matching ""

    No results matching ""