Python Exception Handling (try, except, finally, raise)

Exception handling in Python, is a process of handling an exception raised by the Python program. Following are the keywords used to deal with exception handling in Python:

  • try
  • except
  • finally
  • raise

Sometime exception handling becomes important, to continue the execution of program, to avoid the program halt when an exception is raised.

The try Keyword in Python

The try keyword is used to create try block, that tests the code for errors.

The except Keyword in Python

The except keyword is used to create except block, that handles the raised exception/error.

The finally Keyword in Python

The finally keyword is used to create finally block, that executes all the statements written in this block, without caring whether an exception is raised or not.

The raise Keyword in Python

The raise keyword is used to raise an exception.

Python Exception Handling Examples

All the four keywords that deals with exception handling in Python, are defined. Now it is the time to elaborate with the help of example programs, one by one.

Python try-except Block

The try...except are the two most used keywords while handling exceptions in Python. Because, when we need to check a code for the error, we need a try block, whereas if exception raised, we need to catch that exception, using the except block of course. For example:

try:
    print("The value of variable 'val' is", val)
except:
    print("The variable 'val' is not defined")

Since the variable, val is not defined before its use, therefore the output will be:

The variable 'val' is not defined

While creating a program in Python, if you're not sure about any particular statement, for example, if you want to receive an integer input from user, but as we know the input() method treats every entered value as string type. Therefore we need to cast/convert the value to int type. But what if user enters a value like $, D, #, Python, that can not be converted into the int. Then in that case, we need to put the statement in a try block, so that, we can catch the exception. For example:

print("Enter a number: ", end="")
num = input()

try:
    num = int(num)
    cub = num*num*num
    print("\nCube =", cub)
except:
    print("\nInvalid Input!")

The snapshot given below shows the sample run of above program, with user input 12:

python exception handling

Here is another sample run with user input codescracker. This time, the input is actually a string, that can not be converted into an int type value. Therefore the output will be:

python exception handling try except

Now the question is, what if the program is created without using try-except ?
Let's find out the answer, using the practical program given below:

print("Enter a number: ", end="")
num = input()

num = int(num)
cub = num*num*num
print("\nCube =", cub)

Now the output with user input anything other than a number, say # will be:

python exception try except example

As you can see from above output, the program halts with following statement:

num = int(num)

The name of raised error or exception is ValueError. Therefore, we can caught this exception, using the try-except block in this way:

print("Enter a number: ", end="")

try:
    num = int(input())
    print("\nCube =", num*num*num)
except ValueError:
    print("\nInvalid Input!")

I've also done little modification to short the code. The above code will still produce the same output.

To produce only the error message (the default one) manually, then create the program in this way:

print("Enter a number: ", end="")

try:
    num = int(input())
    print("\nCube =", num*num*num)
except ValueError as ve:
    print("\nInvalid Input!")
    print("Exception:", ve)

Now the output with user input # will be:

python exception try except program

Multiple Exceptions with Same Code in Python

We can use multiple except blocks to catch multiple exceptions raised by the code placed in try block. For example:

try:
    print("The square of", num, "is", num*num)
except NameError:
    print("The variable 'num' is not defined")
except:
    print("Something went wrong!")

Since the variable num is not defined. Therefore when we use an undefined variable/object in Python, it raises an exception named NameError. Therefore the output will be:

The variable 'num' is not defined

Now let's modify the above program with the program given below:

num = "10"
try:
    num = int(num)
    print("The square of", num, "is", num*num)
except NameError:
    print("The variable 'num' is not defined")
except ValueError:
    print("Invalid value stored in variable 'num'")
except:
    print("Something went wrong!")

Since the variable num is defined before its use. Therefore the output will be:

The square of 10 is 100

Let's again modify the above program. That is, initialize anything other than a number say Python to num. For example:

num = "Python"
try:
    num = int(num)
    print("The square of", num, "is", num*num)
except NameError as ne:
    print("The variable 'num' is not defined")
    print("Exception:", ne)
except ValueError as ve:
    print("Invalid value stored in variable 'num'")
    print("Exception:", ve)
except:
    print("Something went wrong!")

Now the output will be:

Invalid value stored in variable 'num'
Exception: invalid literal for int() with base 10: 'Python'

These are just some demos shows the handling of multiple exceptions in Python.

The Syntax to Handle Multiple Exceptions

try:
   # do something
except exceptionName:
   # handle particular exception
except (exceptionOne, exceptionTwo, exceptionThree):
   # handle multiple exceptions at once
except:
   # handle all other (remaining) exceptions

Python try with finally

The finally keyword is used to create a block of code to execute after the try...except block. This finally block of code will get executed, even if try raised an exception. For example:

print("Enter a Number to Print its Table: ", end="")
try:
    num = int(input())
    print("\nTable of", num, ":")
    for i in range(1, 11):
        print(i*num)
except ValueError:
    print("\nInvalid Input.")
finally:
    print("\nProgram finished.")

The sample run with user input 6 is:

python exception try except finally

And the snapshot given below shows another sample run with user input $

python exception try with finally

Note - The finally block always executes, regardless the result of try...except.

Python try with else

The else block after the try...except, can be used to execute statement(s), when no errors raised. For example:

print("Enter a Number: ", end="")
try:
    num = int(input())
except ValueError:
    print("\nInvalid Input.")
else:
    print("\nTable of", num, ":")
    for i in range(1, 11):
        print(num, "*", i, "=", num*i)

The sample run with user input 8 is shown in the snapshot given below:

python exception try except else

Whereas the sample run with invalid user input say fun is shown in another snapshot, given below:

python exception try with else

Python raise Keyword Example

The following program shows an example of raise keyword in Python:

print("Enter a Positive Number: ", end="")

try:
    num = int(input())
    if num<0:
        raise Exception("Negative numbers aren't allowed.")
except ValueError:
    print("\nInvalid Input!")

The sample run with user input -34, a negative number, is shown in the snapshot given below:

python exception raise keyword example

Here is another example, demonstrates the raise statement/keyword in Python:

print("Enter a Number: ", end="")
num = input()

if not type(num) is int:
    raise TypeError("Invalid Input!")

The sample run with user input coding is shown in the following snapshot:

python exception handling raise

Python Online Test


« Previous Tutorial Next Tutorial »