Python try catch exceptions with simple examples

Introduction to try catch exception in Python

A program in python terminates as it encounters an error. Mainly there are two common errors; syntax error and exceptions.

Python exceptions are errors that happen during execution of the program. Python try and except statements are one of the important statements that can catch exceptions. I

Advertisement

n this tutorial we will cover Python exceptions in more details  and will see how python try except statements  help us to try catch these exceptions along with examples. Moreover, we will also learn about some of the built-in exceptions in python and how to use them.

 

Difference between Python Exception and Error

Python exceptions and errors are two different things. There are some common differences between them which distinguish both from each other. These are the following differences between them.

  • Errors cannot be handled, while Python exceptions can be catchd at the run time.
  • The error indicates a problem that mainly occurs due to the lack of system resources while Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the developers.
  • An error can be a syntax (parsing) error, while there can be many types of exceptions that could occur during the execution.
  • An error might indicate critical problems that a reasonable application should not try to catch, while an exception might indicate conditions that an application should try to catch.

 

Different type of errors in Python

Errors are the problems in a program due to which the program will stop the execution. There can be different types of errors which might occur while coding. Some of which are Syntax error, recursion error and logical error. In this section we will closely look at each of these errors in more detail.

 

Syntax error in Python

When we run our python code, the first thing that interpreter will do is convert the code into python bytecode which then will be executed. If the interpreter finds any error/ invalid syntax during this state, it will not be able to convert our code into python code which means we have used invalid syntax somewhere in our code. The good thing is that most of the interpreters show us/give hints about the error which helps us to resolve it.  If you are a beginner to Python language, you will see syntaxError a lot while running your code.

Here is an example showing the syntax error.

# defining variables
a = 10 b = 20

Output:
Python Try Except | Exception Handling Examples

Advertisement

You can see the python is indicating the error and pointing to the error.

 

Recursion error in Python

This recursion error occurs when we call a function. As the name suggests, recursion error when too many methods, one inside another is executed with one an infinite recursion.

See the following simple example of recursion error:

# defining a function:
def main():
   return main()

<i># calling the function</i>
main()

Output:
Python Try Except | Exception Handling Examples

See the last line, which shows the error. We get a recursionError because the function calls itself infinitely times without any break or other return statement.

 

Python exceptions

Sometimes, even if the syntax of the expression is correct, it may still cause an error when it executes. Such errors are called logical errors or exceptions. Logical errors are the errors that are detected during execution time and are not unconditionally fatal. Later in the tutorial we will cover how to catch these errors using python try except method.

Again there can be many different kinds of Python exceptions you may face. Some of them are typeError, ZeroDivisionError, importError and many more. We will see some of the examples of exceptions here.

See the example which gives typeError when we try to add two different data types.

Advertisement
# string data type
name = "bashir"

<i># integer data type</i>
age = 21

# printing by adding int and string
print(age + name)

Output:

Python Try Except | Exception Handling Examples

Here is one more example which gives zeroDivisionError when we try to divide some number by zero.

# zero division
print(23/0)

Output:

    print(23/0)
ZeroDivisionError: division by zero

Now see the last example of import module error. This error occurs when we import a module that does not exist.

# importing module
import abce

Output:

    import abce
ModuleNotFoundError: No module named 'abce'

 

Python try catch exception

In Python, it is possible to write programs that catch selected exceptions. Python try except statements are the most common way to catch Python exceptions. In this section we will cover some of the common ways using python try except methods to catch different exceptions that might occur during the execution time of code.

Before going into the built-in python expedition handling statements, let us first learn how we can raise an exception if a condition is not fulfilled. In Python we use keyword raise to throw an exception. Let us say we want to take integer input from the user, and if the user enters a string value, then the program should throw an exception.

See the following example.

Advertisement
# taking input from user
number = "b"

# checkting type of variable
if type(number)==int:
   pass

# execute else part if the variable if not int type
else:
   raise TypeError("Only numeric values are required!!")

Output:

  raise TypeError("Only numeric values are required!!")
TypeError: Only numeric values are required!!

 

Python try except method to catch exception

As we already know that when syntactically correct code runs into an errors, then Python will throw an exception error. This exception will crash the program if not handled. The except clause determines how our program responds to exceptions.

Python try and except statements are used to catch and handle such exceptions. Python will first execute the try statement as a normal part of the program. If it successfully executes the try block, then it will not go to the except block. If the program catches any error during execution of the try block, then the execution of the program will shift to the except block.

 

Python try catch syntax

Python syntax to perform a try and catch can be achieved using following  try except block looks like this:

try:
   ## do normal statement
except Exception:
   ## handle the error

 

Example to catch exception with python try except

Let us now take a real example and try to divide some numeric value by zero. We know that if we do not handle the zeroError our code will crash and will give us errors. See the example below how we managed to catch zeroError using Python try and except block.

# Python try and except method
try:
   print(23/0)

# Execute except block if zero division occurs
except ZeroDivisionError:
   # handle zero division error
   print("Cannot divide by zero!")

Output:

Cannot divide by zero!

Notice that our program executes successfully in spite of facing zeroDivisionError.

In a similar way we can catch other exceptions that occur during execution of a program. Let us catch the import error that occurred during the import of unknown or uninstalled modules.

# Python try and except method
try:
   import abcd

# execute except block if import error occurs
except ImportError:
   # handle import error
   print("Unable to import module!!")

Output:

Unable to import module!!

See the following example which catchs the TypeError that occurs in Python when we try to add an integer with string.

# Python try and except method
try:
   print(12 + "bashir")

# excute except block if type error occurs
except TypeError:
   # handle type error
   print("Strings cannot be added to integer")

Output:

Strings cannot be added to integer

 

Python try except with ELSE to catch exception

The Python else clause is useful when we want to run a piece of code only when there will be no error or exception. Because The code inside the else block will be only executed  if the try clause does not raise an exception.

 

Python try and catch with else syntax

See the simple syntax of python try catch with else statement.

# try block
try:
    # statements run if no exception occurs
except (name_of_exception):
    # Handle exeption
# Else block only executes if no exception occurs
else:
    # else statements 

 

Python try and catch with else example

Now let us take a practical example to implement python try catch with else block. See the following example where the else statement will only be executed if there will be no exception.

#  Python try and except method
try:
   number = 24/6

# execute except block if zero division occurs
except ZeroDivisionError:
   # hanlde exception
   print("Cannot divide by")

# Run this else block if no exception occurs
else:
   print("the answer is {}".format(number))

Output:

the answer is 4.0

If we try to divide the number by 0 it will raise an exception and the else statement will not be executed. See the example below:

#  Python try and except method
try:
   number = 24/0

#execute except blcok if zero division occurs
except ZeroDivisionError:
   # handle exception
   print("Cannot divide by zero")

# Executes else block only if no exception occurs
else:
   print("the answer is {}".format(number))

Output:

Cannot divide by zero

Let us take one more example of the importing module as well using the python try except and else statement.

#  Python try and except method
try:
   import math

# Execute except block if module error accurs
except ModuleNotFoundError:
   print("no module found!!")

# Execute else block only if no exception occurs
else:
   print(math.pow(2, 3))

Output:

8.0

You can notice that the else statement in python try except only executes when the program does not produce any exceptions.

 

Python try expect with FINALLY to catch exception

We might come across a situation in our program when we want to execute the program even if an exception occurs. We can achieve this either by writing the piece of code in try and except both blocks ( which is not  recommended when we have a large amount of code) or we can use the keyword finally. Finally, the statement is opposite of else , it always executes after try and except blocks.

 

Python try and catch with finally syntax

Here is simple syntax of python try catch with finally block.

# try block
try:
    # statements run if no exception occurs
except (name_of_exception):
    # Hanlde exception
# this block will be executed always
# independent of except status
finally:
    # final statements

 

Python try and catch with finally example

See the example below which uses finally block along with python try except.

#  Python try and except method
try:
   number = 24/0

# execute except block if zero division occur
except ZeroDivisionError:
   print("Cannot divide by zero")

# Always run finally block
finally:
   print("This block successfully was executed!")

Output:

Cannot divide by zero
This block successfully was executed!

Notice that even our code produces ZeroDivisionError but still the finally block was executed successfully.

Now let us take one more example of importing a module without any exception.

# Python try and except method
try:
   import math

# run except block if module error occurs
except ModuleNotFoundError:
   print("No module exist")

# Always run finally block
finally:
   print("Good job!")

Output:

Good job!

 

Multiple EXCEPT clauses to catch exceptions in Python

So far in each example we have used only one except block. However, Python allows us to use multiple except blocks as well. While executing the try block if there is an exception, then the very first exception block will be considered, if the first except block catchs the exception, others will not be executed, else each except blocks will be checked respectively. Multiple except clauses are helpful when we are not sure about the type of exception that might occur.

 

Syntax to catch multiple exceptions

Here is the simple syntax of multiple except clauses.

# try and catch block
try:
    # run try statements if no exception occurs

# run this block if exception_one occurs
except exception_one:
    # handle exception_one

# run this block if exception_two occurs
except exception_two:
    # hanlde exception_two

.
.
.

# run this block if exception_n occurs
exception exception_n:
    # handle exception_n

 

Examples to catch multiple exceptions in Python

See the example below which uses multiple except blocks in Python.

#  Python try and except method
try:
   import math
   number = 24/6
   print(number)

# run except block if module error occur
except ModuleNotFoundError:
   print("No module exist")

# run except blcok if zero division occurs
except ZeroDivisionError:
   print("Cannot divide by zero!")

# Always run finally block
finally:
   print("Good job!")

Output:

4.0
Good job!

Now let us import an unknown module. See the example below:

#  Python try and except method
try:
   import abcd
   number = 24/6
   print(number)

#run except block if module error occurs
except ModuleNotFoundError:
   print("No module exist")

# run this block if zero division occurs
except ZeroDivisionError:
   print("Cannot divide by zero!")

# Always run finally block
finally:
   print("Good job!")

Output:

No module exist
Good job!

 

The assertError exception handling in Python

Instead of waiting for a program to crash midway, we can also start making precautions by making assertions in Python. We can assert a condition that if this condition is met to be true then execute the program. And if the condition turns out to be False, we can have a program to throw an assertion error exception.

See the following example which shows how assertion works in Python

try:
   denominator = 0
   assert denominator != 0, "Cannot divide by zero"
   print(24/ denominator)
 
# executes the assertionError if assert condition is false
except AssertionError as msg:
   print(msg)

Output:

Cannot divide by zero

 

Summary

Python exceptions are inherited from the class BaseException. Exceptions are throw by the interpreter while executing the programming and crashes when it come across any exception. In order to run our program successfully it is very important to catch such exceptions. In this tutorial we covered python exceptions, difference between and error and exceptions. Moreover, we learned about python try except statements to catch expectations and also come across some of the important python built-in exceptions.

 

Further Reading

Python exceptions
try and except statement
More about python exceptions

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment