Python Exception Handling – Try/Except Block, Finally Block

Free Python courses with 57 real-time projects - Learn Python

In our previous lesson on Errors and Exceptions in Python. Now, we are going to explore Python Exception Handling.

Here, we will discuss try/except blocks, finally block, and raise block. Along with this, we will learn how to define your own python exception.

So, let’s begin Python Exception Handling.

Exception Handling in Python

Python Exception Handling

What is Exception Handling in Python?

As we have already seen different types of exceptions in python, let us see various ways for Python exception handling if we get any python exception while programming in python.

The try/except blocks

When you think a part of your code might throw an exception, put it in a try block.

Let us see a Python try exception example.

try:
            for i in range(3):
                        print(3/i)
except:
            print("You divided by 0")
     print(‘This prints because the exception was handled’)

Output

= RESTART: C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\try2.py =

You divided by 0

This prints because the exception was handled

What follows is an except block. When you don’t specify which exception to catch, it will catch any. In other words, this is generic for exceptions.

When an exception is thrown in a try block, the interpreter looks for the except block following it. It will not execute the rest of the code in the try block.

Python Exceptions are particularly useful when your code takes user input. You never know what the user will enter, and how it will mess with your code.

1. Python Multiple Excepts

It is possible to have multiple except blocks for one try block. Let us see Python multiple exception handling examples.

>>> a,b=1,0
>>> try:
          print(a/b)
          print("This won't be printed")
          print('10'+10)
except TypeError:
          print("You added values of incompatible types")
except ZeroDivisionError:
          print("You divided by 0")

Output

You divided by 0

When the interpreter encounters an exception, it checks the except blocks associated with that try block.

These except blocks may declare what kind of exceptions they handle. When the interpreter finds a matching exception, it executes that except block.

In our example, the first statement under the try block gave us a ZeroDivisionError.

We handled this in its except block, but the statements in try after the first one didn’t execute.

This is because once an exception is encountered, the statements after that in the try block are skipped.

And if an appropriate except block or a generic except block isn’t found, the exception isn’t handled.

In this case, the rest of the program won’t run. But if you handle the exception, the code after the excepts and the finally block will run as expected.

Let’s try some code for this.

a,b=1,0
try:
   print(a/b)
except:
   print("You can't divide by 0")
print("Will this be printed?")

Output

== RESTART: C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\try.py ==
You can’t divide by 0
Will this be printed?
>>>

2. Python Multiple Exception in one Except

You can also have one except block handle multiple exceptions. To do this, use parentheses. Without that, the interpreter will return a syntax error.

>>> try:
      print('10'+10)
      print(1/0)
except (TypeError,ZeroDivisionError):
      print("Invalid input")

Output

Invalid input

3. A Generic except After All Excepts

Finally, you can compliment all specific except blocks with a generic except at the end.

This block will serve to handle all exceptions that go undetected by the specific except blocks.

>>> try:
           print('1'+1)
           print(sum)
           print(1/0)
except NameError:
           print("sum does not exist")
except ZeroDivisionError:
           print("Cannot divide by 0")
except:
           print("Something went wrong")

Output

Something went wrong

Here, the first statement under the try block tries to concatenate a string to an int. This raises a TypeError.

As the interpreter comes across this, it checks for an appropriate except block that handles this.

Also, you can’t put a statement between try and catch blocks.

try:
   print("1")
print("2")
except:
   print("3")

This gives you a syntax error.

But there can only be one generic or default except block for one try block. The following code gives us “default ‘except:’ must be last”:

try:
       print(1/0)
except:
       raise
except:
       print("Raised exception caught")
finally:
       print("Okay")
print("Bye")

Finally Block in Python

Optionally, you may include a finally exception block after the last except block. The code under this block executes in all circumstances.

>>> try:
        print(1/0)
except ValueError:
        print("This is a value error")
finally:
        print("This will print no matter what.")

Output

This will print no matter what.
Traceback (most recent call last):File “<pyshell#113>”, line 2, in <module>
print(1/0)
ZeroDivisionError: division by zero

Note that the Python exception message is printed after the finally block executes. Now you may think, why don’t we just use a print statement instead?

As you can see in the previous example, ‘finally’ runs even when we fail to catch the exception that occurs. Now what if an exception occurred in except?

>>> try:
        print(1/0)
except ZeroDivisionError:
        print(2/0)
finally:
        print("Sorry, not happening")

Output

Sorry, not happening

Traceback (most recent call last):File “<pyshell#122>”, line 2, in <module>

print(1/0)

ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Output

Traceback (most recent call last):File “<pyshell#122>”, line 4, in <module>

print(2/0)

ZeroDivisionError: division by zero

So as you can see, the code under the finally block executes no matter what.

Raise Keyword in Python

Sometimes, you may want to deal with a situation by raising a certain exception. A simple print statement won’t work here.

>>> raise ZeroDivisionError

Output

Traceback (most recent call last):File “<pyshell#132>”, line 1, in <module>

raise ZeroDivisionError

ZeroDivisionError

Let’s take our case of division.

>>> a,b=int(input()),int(input())

Output

10

>>> if b==0:
        raise ZeroDivisionError

Output

Traceback (most recent call last):File “<pyshell#140>”, line 2, in <module>

raise ZeroDivisionError

ZeroDivisionError

Here, we convert the inputs to a and b to integers. Then, we check if b is 0. In that case, we raise a ZeroDivisionError.

Now what if we put this in try-except blocks? Let’s make a .py file for it.

a,b=int(input()),int(input())
try:
       if b==0:
             raise ZeroDivisionError
except:
   print("You divided by 0")
print("Will this print?")

When we run this using Fn+F5, we get the following output:

= RESTART: C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\try2.py =1

0

You divided by 0

Will this print?

We’ll take just one more example before moving on.

>>> raise KeyError

Output

Traceback (most recent call last):File “<pyshell#180>”, line 1, in <module>

raise KeyError

KeyError

1. Raise Without a Specified Exception in Python

It is possible to use the raise keyword without specifying what exception to raise. Then, it reraises the exception that occurred.

This is why you can only put it in an except block.

>>> try:
         print('1'+1)
except:
         raise

Output

Traceback (most recent call last):File “<pyshell#152>”, line 2, in <module>

print(‘1’+1)

TypeError: must be str, not int

2. Raise With an Argument in Python

Additionally, you can provide an argument to the specified exception in raise.

You can do this to give out additional details about the exception.

>>> raise ValueError("Inappropriate value")

Output

Traceback (most recent call last):File “<pyshell#156>”, line 1, in <module>

raise ValueError(“Inappropriate value”)

ValueError: Inappropriate value

Assertions in Python

An assertion is actually a sanity-check for your cynical, paranoid soul.

It takes an expression as an argument and raises a python exception if the expression has a False Boolean value.

Otherwise, it performs a No-operation (NOP).

>>> assert(True)
>>>

Now what if the expression was False?

>>> assert(1==0)

Output

Traceback (most recent call last):File “<pyshell#157>”, line 1, in <module>

assert(1==0)

AssertionError

Let’s take another example, and let’s create a .py file for that.

try:
       print(1)
       assert 2+2==4
       print(2)
       assert 1+2==4
       print(3)
except:
       print("An assert failed.")
       raise
finally:
       print("Okay")
print("Bye")

Output

= RESTART: C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\try2.py =1

2

An assert failed.

Okay

Traceback (most recent call last):File “C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\try2.py”, line 5, in <module>

assert 1+2==4

AssertionError

Interestingly, if you remove the raise from under the except block, this is the output:

= RESTART: C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\try2.py =1

2

An assert failed.

Okay

Bye

This is because when we ‘raise’ an exception, we aren’t provisioning a handle for it.

We can use assertions to check for valid input and output to functions.

1. A Second Argument to assert

You may optionally provide a second argument to give out some extra information about the problem.

>>> assert False,"That's a problem"

Output

Traceback (most recent call last):File “<pyshell#173>”, line 1, in <module>

assert False,”That’s a problem”

AssertionError: That’s a problem

Defining Your Own Exceptions in Python

Finally, we’ll talk about creating our own exceptions. For this, we derive a new class from the Exception class.

Later, we call it like any other exception.

>>> class MyError(Exception):
print("This is a problem")
>>> raise MyError("MyError happened")

Output

Traceback (most recent call last):File “<pyshell#179>”, line 1, in <module>

raise MyError(“MyError happened”)

MyError: MyError happened

This was all about the Python Exception Handling Cheat Sheet.

Python Interview Questions on Exception Handling

  1. What is Python exception handling? Explain with example.
  2. Why exception handling is important in Python?
  3. How to handle multiple exceptions in Python?
  4. How does Python handle value exception?
  5. What is the purpose of  try and catch in Python exception handling?

Conclusion

After this article, we hope you’ll play safer with your code. This is because now you can do Python Exception Handling, raise it, and even create your own.

If you’d like to add your own code on Python Exception Handling to the comments, we’d love to hear.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

3 Responses

  1. Mayur says:

    It is really good, concise and helful information on exception handling!

    • DataFlair Team says:

      We are thankful for your kind words. If you really liked our tutorial please don’t forget to share with as many people as possible.

  2. Prashantha Rao says:

    fantastic!!! thanks

Leave a Reply

Your email address will not be published. Required fields are marked *