Exceptions

An exception is an error that occurs while a program is running, causing the program to abruptly halt. We want to "handle" these exception errors. We use the try/except statement to handle exception errors. We can do this with if-else statement as well.

We also have as part of the try/except statement is the finally clause:

try:

    statement

    statement

    etc.

except ExceptionName:

    statement

    statement

    etc.

finally:

    statement

    statement

    etc.

Exception Handling

We have seen plenty of errors in previously when something goes wrong or some input was given erroneously. In such cases, it might be preferred to inform the user on the error and give a chance to correct it.

We can use the try-except construct to handle the error.

info

The example below are written in "script" mode.

Example: user_input_exception.py

while True:
    try:
        usr_num = int(input("Enter an integer number: "))
        break
    except ValueError:
        print("Not an integer, try again")

print("Square of entered number is: {}".format(usr_num * usr_num))

except can be used for particular error (in this case ValueError).

Results:

Enter an integer number: a
Not an integer, try again
Enter an integer number: 1.2
Not an integer, try again
Enter an integer number: 3
Square of entered number is: 9

Further Reading