Python try exception Complete Tutorial

In this section, we will learn what try exception is and how to use it in Python.

Exception in Python: What is an Exception and How to Raise Exception in Python?

Anything in a program that causes that program to derail from its normal process of instruction execution and led to the crash of the program is considered as an error or exception.

For example, let’s say we have a program and its job is to take multiple numbers and multiply them to each other and finally return the result! Now let’s say instead of number, we pass it a value of type string for example! Now if the program is not properly written to handle other data types, then it will throw an exception in this case and finally crash.

To give you another simple example, consider a program that takes two numbers from a user and then divide those values to each other. Now consider the scenario where a user put the two values 4 and 0 so that 4 becomes divided by 0! This is another source of exception and will cause our program to crash (because numbers should not be divided by 0)!

Example: raising exceptions in python

val1 = 0

val2 = 4

res = val2/ val1

print(res)

Output:

ZeroDivisionError: division by zero

As you can see, this little program crashed because of the attempt to divide the value 4 by 0!

Python try except (AKA Python try catch): Handling Exceptions in Python

The method of controlling exceptions from crashing a program is called exception handling!

In Python we use `try except` statements to handle a potential exception that might occur in our program.

Let’s see how to create and use `try except` statements in a program.

Python try except Syntax and Declaration

try:
    #body…
except ExceptionName: 
    #body...

try and except handler in Python

In order to create an exception handler, we first start with the keyword `try`. Now the indented lines below this try statement will be considered as part of the try block.

The `try` block is the place where we put the risky codes that might raise an exception. Basically, we should put the part of a code that might throw an exception within the body of this try statement.

Usually, with each `try` block, comes at least one `except` handler block. This handler is the place where we define the instructions to be executed when an exception is thrown within the body of the related `try` block!

After the `except` keyword, we put the name of an exception that we want to handle. For example, if the target try block has a set of instructions that might throw `ZeroDivisionError` exception (as a result of dividing a number by zero) then we can set the name of this exception on the right side of the `except` keyword and so the handler will be executed only if the `ZeroDivisionError` exception is thrown in the try block.

Notes:

  • We put the `except` statement right after the body of the related try block that wants to handle its potential exception.
  • An except handler will only run if there’s an exception within the related `try` block.
  • But if the body of the target try block ran properly, then none of the handler will be executed. Basically, in a situation like this, the Python execution engine will simply move to the instructions after the body of the handlers and continue to run those instructions.

Example: exception handling in python with python try clause

try:
    print(10/0)
    print("This message will never get printed")
except ZeroDivisionError: 
    print("A value is divided by zero")

print("The instructions after the try block")

Output:

A value is divided by zero

The instructions after the try block

In this example, the instruction within the body of the `try` statement is clearly an error because we’re trying to divide a number by 0!

The exception that will be thrown is called ZeroDivisionError. So what we’ve done here is that we’ve created a handler that will be called only if the instructions within the body of the related try block throw the `ZeroDivisionError` exception (as it happened for this simple program).

Note:

  • When an exception happens in the body of a try block, the execution engine will stop running the instructions in the body of the try block and will move on to the body of the related handler of that try block.
  • Now, after handling the exception, the execution engine will never return to the try block! It simply moves on to the instructions after the handler. In the example above, the instructions after the handler is a call to the print() function and as you see from the output, this function is called directly after the body of the handler gets executed. Also note that the statement `print(“This message will never get printed”)` never executed! This is a proof that when an exception arises in a try block, the rest of instructions in that block are skipped.

Python except as

When an exception is thrown in Python, that exception is basically an object! Now, if we want to access the exception object within the body of the target handler, we can use the `as` keyword to create an alias, which will represent the thrown exception.

Example: handling errors in python

try:
    print(10/0)
except ZeroDivisionError as z: 
    print(z)

print("The instructions after the try block")

Output:

division by zero

The instructions after the try block

Each Exception object has a message that describes the reason for exception! Now, by using the `as` keyword and accessing the target exception object, we can pass the object as the argument to functions like `print()` and get the message.

try except else Python

The `try` handler can also have an optional `else` statement.

This `else` statement will be executed if no exception occurred within the body of the related try block. But remember, if an exception is thrown in the `try` block, then the `else` statement will be ignored.

Example: try except else python

try:
    print("Hello World")

except Exception as e: 
    print(e)
else:
    print("No exception is thrown within the body of the try block")

print("The instructions after the try block")

Output:

Hello World

No exception is thrown within the body of the try block

The instructions after the try block

Python try finally

Sometime we want to run a set of instructions no-matter if an exception is occurred in a program or not. For example, when working with files, it is important to close those files after working with them! So now consider that you’ve opened a file, but then an exception occurred within your program! How can you make sure that this exception won’t affect the closing operation of the target file?

This is where we can use the `finally` block!

Each try block can have one optional `finally` block and it is guaranteed that the body of this block will get executed no matter if an exception is thrown or not.

So within the body of a finally block, we can put any necessary instructions and be rest assured that these instructions will be executed.

Example: try finally in python

try:
    raise Exception("This is a manual exception")
except Exception as e: 
    print(e)
else:
    print("No exception is thrown within the body of the try block")
finally:
    print("The message from the finally block")

print("The instructions after the try block")

Output:

This is manual exception

The message from the finally block

The instructions after the try block

Python Catch Multiple Exceptions

Now, because potentially a block of code might throw more than just one exception, it is possible to add multiple `except` blocks as part of a try statement.

For example:

try: 
except ExceptionName: 
except ExceptionName2: 
except ExceptionNameN:

In this case, if an exception is thrown within the body of the `try` block, then Python will check the `except` handlers to see which one matches the thrown exception. Now, if it finds one, it will run the body of that handler.

Notes:

  • Only the matched exception handler will run as a result of an exception that is thrown within the body of the related try block! This means if there are multiple handler but not related to the thrown exception, then they will be ignored.
  • If the target try block raised an exception and none of the handlers could handle the exception, it might lead to a program crash if there’s no other handler within the enclosing scopes.

To explain the enclosing scopes a bit more:

Consider a function named A. Within the body of this function, we’ve created a try to except block and in the body of the `try` we’ve called another function called B.

Now the body of the function B also has a `try` and `except` handler blocks as well. So let’s say an exception is thrown within the body of the try block in the function B. But the handler in the B function could not handle the exception!

In that case, the Python execution engine (interpreter) will close the body of the function B and returns to the caller of this function which is the function A.

Now because the function A called the function B within a try block, then Python will check the handlers of the try block to see if there’s a handler that matches the thrown exception. If there was one, then it will run that handler and after that continues to execute instructions after the body of this handler exception in the function A or return to the caller of the function A if there’re no instructions to run.

BTW, if the function A is also not capable of handling the thrown exception, then Python will terminate the function A immediately (it won’t run any instructions other than handling the thrown exception first) and it will return to the caller of the function A which could be a statement in the global scope for example.

Now, if in this scope also there wasn’t a proper handler for the exception, then finally Python will send an error message to the output stream and stop the program from running.

  • An exception handler is capable of handling more than one exception. To do this, we must put a pair of parentheses after the except keyword and put the list of exceptions that want to handle in that pair of parentheses and separate each exception’s name with a comma:
except ( ExceptionName1, ExceptionName2, ExceptionNameN):
    #body… 

Example: python multiple exceptions

import random 

list1 = [1,2,3,4,5]
try:
    res = random.choice(list1)
    if res <= 3:
        print(10/0)
    else:
        print(list1[10])

    print("This message will never get printed")

except ZeroDivisionError: 
    print("A value is divided by zero")
except IndexError: 
    print("You're tring to access the element in an index position that doesn't exist!")
    
print("The instructions after the try block")

Output:

You're tring to access the element in an index position that doesn't exist!

The instructions after the try block

Note: the `choice()` function of the random module takes a sequence of elements as its argument and returns a random element of that sequence as a result.

In this little program, two types of exceptions might be thrown. The first one is `ZeroDivisionError` which will be thrown if a number is divided by zero. The other potential exception is `IndexError`. This second exception will be thrown if we try to access an element of a list in a position that is out of range of that list object.

Now, as you can see, we’ve added two handlers for this program and each one of them will handle one of these exceptions. So now if the program thrown the `ZeroDivisionError` exception, then the first handler will be executed. Also, if the program throws the `IndexError` then the second handler will be executed as a result.

Python Catch All Exceptions

Note that we can set an exception handler for a `try` block without any specific exception! In that case, the target exception handler becomes the default handler and will be executed if there’s no specific handler is set for that try block related to the thrown exception or if there are specific handlers but none of them can handle the thrown exception in the target `try` block.

Note: because the default handler is capable of handling any type of exception, it should come as the last handler if the target try block has more specific exception handlers as well.

Example: catch all exceptions in python

import random 

list1 = [1,2,3,4,5]
try:
    res = random.choice(list1)
    if res <= 3:
        print(10/0)
    else:
        print(list1[10])

    print("This message will never get printed")

except: 
    print("An exception is thrown which could be either ZeroDivisionError or IndexError but we don't know which one! ")


print("The instructions after the try block")

Output:

An exception is thrown which could be either ZeroDivisionError or IndexError but we don't know which one!

The instructions after the try block

The `except` handler in this example is a default one and because this is the only handler in this example, it will run no-matter what type of exception is thrown in the target try block.

Python raise Exception (Throw Exception in Python):

Other than automatically done by Python, we can throw an exception in a program manually as well! This is called raise an exception and it’s done using the `raise` keyword.

Now, in order to throw an exception, all we need to do is to call the `raise` statement and create an exception on the right side of this keyword.

Note: The entire exceptions in Python are inheriting from the Exception class. So if we want to create a general exception, all we need to do is to create an object of type of this class and put the reason of the exception (a string value) as the argument of this class as:

raise Exception (“this is a manual exception”)

Example: raising exception in Python

import random 

list1 = [1,2,3,4,5]
try:
    res = random.choice(list1)
    if res <= 3:
        raise Exception("The value is less than 3 or equal to 3!")
    else:
        print(list1[10])

    print("This message will never gets printed")

except Exception as e: 
    print(e)

print("The instructions after the try block")

Output:

The value is less than 3 or equal to 3!

The instructions after the try block

In this example, if the value of the `res` variable is less than 3, we will throw an exception using the `raise` statement.

Difference between Error and Exception

Note that there are differences between Error and Exception!

An error happens when the Python interpreter is reading our source code and it finds a syntax error or something that it can’t interpret! Basically, errors happen before the execution of the code!

For example:

try
    pass

except Exception as e: 
    print(e)

print("The instructions after the try block")

Output:

SyntaxError: invalid syntax

In this example, we got an error because of not using a colon after the `try` keyword! Note that Python didn’t run any statement!

On the other hand, an exception is a failure that happens while the program is running! For example, because of a bad input from users, a failure to connect to an external resource, etc.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies