How To Throw Exceptions In Python

April 28, 2023
How to Throw Exceptions in Python



Overview

It is inevitable for Software applications to run perfectly all the time. Despite a series of debugging and testing levels, it is quite possible that applications still fail. poor network connectivity, corrupted databases, incorrect data, memory pressures, and unexpected user inputs can all lead an application to raise an exception. If these exceptions are not handled well, it can cause the program to crash, and as a result, you can lose data or it can get corrupted.

python CTA

Exceptions in Python

Exceptions in Python applications can also occur due to the above-stated reasons and various other. It is the job of a Python developer, to think about possible exception scenarios and include proper error handling in your code.

Fortunately, Python offers a robust error-handling framework. Python applications can determine the type of error at run time using structured exception handling and a set of pre-defined exceptions. These exceptions then result in actions such as taking an alternate path, use of default values instead of inputs or prompting again for correct input.

We will be discussing in this article, how you can raise exceptions in your Python code and how to address them.

How to Throw an Exception in Python

In numerous cases, it is required to throw a custom exception for error handling in python. It can be done by checking the condition and raising an exception if the condition is True. The raised exception warns the user or the calling application. The “raise” keyword is used to throw a Python exception manually. It also allows the inclusion of a message to describe the exception.

See this simple code snippet below where the user has to enter a date. It has to be a present or a date in the future. If a past date is entered by the user, the program is supposed to throw an exception:

1. from datetime import datetime

2. current_date = datetime.now()

3. print("Today’s date is: " + current_date.strftime('%Y-%m-%d'))

4. dateinput = input("Enter date in dd-mm-yyyy format: ")

5. date_provided = datetime.strptime(dateinput, '%d-%m-%Y')

6. print("Date provided is: " + date_provided.strftime('%d-%m-%Y'))

7. ifdate() < current_date.date():

8. raise Exception("Past date cannot be entered")

To test this code, if a past date was entered. The “if” condition will evaluate to true and an exception will be raised:

Current date is: 12-02-2023

Enter date in dd-mm-yyyy format: 03-01-2022

Date provided is: 03-01-2022

Traceback (most recent call last):

  File "Throw Exception Python01.py", line 8, in

    raise Exception("Past date cannot be entered")

Exception: Past date cannot be entered

Process finished with exit code 1

Instead of raising a simple exception, a type can also be specified for it,

if (date_provided.date() < current_date.date()):

    raise ValueError("Past date cannot be entered ")

With an incorrect input as before, Python will now throw this exception:

raise ValueError("Past date cannot be entered ")

ValueError: Past date cannot be entered

Python Syntax Errors VS Python Exceptions

This question is often raised about the difference between a syntax error and an exception as both are very similar unwanted conditions in Python. The syntax error exception occurs when the code does not comply with the python coding syntax. The interpreter identifies the invalid syntax during translation and raises a SyntaxError exception. As a result, the program stops and crashes at the point where the syntax error occurred. There is also no possible way to handle a syntax error and the program would simply crash.

See this basic example code with a syntax error:

1. Num1 = 34

2. Num2 = 15

3. if (num1 < num2)

4. print('num1 is smaller than num2')

5. elif (num1 > num2)

6. print('num1 is smaller than num2')

7. else

8. print('it’s a Draw')

The interpreter picks up the error and points out the line number.  It also does not proceed after the syntax error so all the proceeding syntax errors will not be identified:

File "Throw Exception Python02.py", line 4

    if (num1 < num2)

             ^

SyntaxError: invalid syntax

Process finished with exit code 1

On the contrary, an exception occurs when the code does not have a syntax error but it comes across other error conditions. These conditions can be addressed within the code (either in the current function or in the calling stack).  Exceptions can be gracefully handled, preventing the code from crashing.

Here is an example of a Python code that does not have any syntax error but it is attempted to perform an arithmetic operation on two string variables:

str1 = 'eighty five'

str2 = 'seventy two'

print(str1 * str2)

The exception that will be raised upon execution is TypeError:

Traceback (most recent call last):

  File "Throw Exception Python03.py", line 4, in

    print(str1 * str2)

TypeError: not all arguments converted during string formatting

Process finished with exit code 1

Python throws the TypeError exception in case of a data type mismatch. There are numerous built-in exceptions in python like MemoryError, ModuleNotFoundError, ImportError, OSError, SystemError and so on.

Using AssertionError in Python Exception Throwing

Another way to raise an exception in python is by assertion. It allows asserting a condition to be true before running a statement. If the condition turns out to be true, the statement runs, and the control is passed to the next statement but if the condition evaluates to false, the program throws an AssertionError.

The previous date example is rewritten below using the assertion:

1. from datetime import datetime 

2. current_date = datetime.now()

3. print("Current date is: " + current_date.strftime('%d-%m-%Y'))

4. dateinput = input("Enter the date in dd-mm-yyyy format: ")

5. print("Date entered: " + date_provided.strftime('%d-%m-%Y')) 

6. assert(date_provided.date() >= current_date.date()), "Date provided can't be in the past"

It is to be noted that the “if” condition has been replaced with asserting When inputting a past date, the AssertionError will display the following message:

Current date is: 12-02-2023

Enter date in dd-mm-yyyy format: 12-02-2023

Traceback (most recent call last):

Date provided is: 02-01-2023

  File "Throw Exception Python04.py", line 9, in

assert(date_provided.date() >= current_date.date()), "Past date cannot be entered"

AssertionError: Past date cannot be entered

Process finished with exit code 1

Exceptions Handling in python

After discussing how to raise exceptions in Python, we will be now looking into ways of handling them. You must have heard about the “try-catch” construct that is commonly used in various modern programming languages for exception handling. However, we use “try-except” in python. Take a look at the syntax of the try-except block below:

try:

    # Lines of code #

except:

    # exception handling code #

# Lines of code #...

the program first enters the “try” block. If an exception occurs, the control is transferred to the code in the “except” block. The error handling code in the “except” block must depend on the type of error you are expecting to encounter.

You can also include multiple “except” blocks for a single “try” block to deal with different types of exceptions. Each “except” block will handle a specific type of error:

try:

    # Lines of code #

except: # exception  type a

    # exception handling code for type a #

except: # exception  type b

    # exception handling code for type b #

except: # exception  type c

    # exception handling code for type c #

except: # exception  type d

    # exception handling code for type d #

...

See this code snippet below:

1. num0 = 10

2. 

3. try:

4. num1 = input("Enter 1st number:")

5. num2 = input("Enter 2nd number:")

6. answer = (int(num1) * int(num2))/(num0 * int(num2))

7. except ValueError as vError:

8. print(vError)

9. exit()

10. except ZeroDivisionError as zdError:

11. print(zdError)

12. exit()

13. except TypeError as tError:

14. print(tError)

15. exit()

16. except:

17. print('Unknown Error!')

18. exit()

19. int(answer)

Python offers the following two extensions of the “try-catch” construct,

Try-Except-Else:

It is very much the same as the previous example however the “else” block is executed at the end if there are no exceptions raised from the “try” block.

See Also: How To Implement Caching In Python?

Try-Except-Else-Finally:

Here, the “Finally” block is the last optional block in Python error handling. It is used after the “else” block (the else block is optional). It is executed regardless of whether the “try” block raises an exception. If an exception is raised, the code in the “except” block will be executed first, and then the code in the “finally” block will run. If there are no exceptions, the code in the “else” block will run, and then the code in the “finally” block will run. As the “finally” block always runs, it is commonly used to conclude the code. The tasks like resetting counters or lists, closing the opened files or closing the database connections etc

Here is an example of using “else” along with “finally”:

1. try:

2. file = open("myfile.txt", 'r')

3. except FileNotFoundError as fnError:

4. print(fnError)

5. print('Creating a new file...')

6. file = open("myfile.txt", 'w')

7. file.write('x')

8. else:

9. data=f.readline(1)

10. print(data)

11. finally:

12. print('Closing the file')

13. file.close()

The “try” block attempts to open a file for reading. If the file does not exist, the exception block shows a warning message, it then creates the file, and writes a value “x” into it. If the file exists, the “else” block reads the first line of its content and prints it.  Finally, the “finally” block closes the file. This will be executed regardless of whether or not the file initially existed.

python CTA2



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US