In this Python tutorial, we will learn how to handle exceptions and raise exception values in Python. A few types of errors and exceptions we will cover are syntax errors, handling exceptions, and raising exceptions. The ability to hand exceptions and errors when creating a Python program is very important on the programs success and the ability to meet a users requirements or the goal of program to succeed.
What are Python Syntax Errors?
Syntax errors in Python are also known as parsing errors and are the most common type of errors or exceptions when writing Python programs. This part of the learning process when starting to learn Python and will take time to learn the correct syntax of Python.
Syntax Error Example
1 2 | >>> while True print('Hello world') SyntaxError: invalid syntax |
Correct While Loop without Syntax Error
1 2 3 4 5 6 7 8 | x = 1 y = 4 while x <= y: print(f"x is {x} ") x += 1 print(f"x is now greater than y : {x} < {y} ") |
Output:
1 2 3 4 5 | x is 1 x is 2 x is 3 x is 4 x is now greater than y : 5 < 4 |
The reason why the while loop has a syntax error is because the while lop is missing a colon and proceed by the print() statement. A while loop must be followed by a colon for proper Python syntax.
What are Python Exceptions?
Python has built-in exceptions which will force a Python program to product an output errors when the program faults. When these exceptions occur, it will cause the current process in the Python program to stop and pass to the process of handling exceptions until the exception is handled, or failure will occur.
Even if you have no syntax errors, the program may throw an exception when attempting to execute the program. When errors are detected during the execution of a Python script, even if it’s unconditionally fatal, are called exceptions. There are way to handle such exceptions and we will provide a few examples on handling Python exceptions.
Python ZeroDivisionError Exception Example:
1 2 3 4 5 | >>> 5 * (2/0) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> 5 * (2/0) ZeroDivisionError: division by zero |
By reading the exception, we can see that division by zero is an exception. This exception name is ZeroDivisionError and is raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation.
Python NameError Exception Example:
1 2 3 4 5 | >>> 5 - python * 2 Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> 5 - python * 2 NameError: name 'python' is not defined |
The above NameError exception is raised when a local or global name is not found. This applies only to unqualified names and the associated value is an error message that includes the name that could not be found.
Python TypeError Exception Example:
1 2 3 4 5 | >>> "3" + 5 + "1" Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> "3" + 5 + "1" TypeError: can only concatenate str (not "int") to str |
The TypeError exception is raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.
How to Handle Exceptions
When writing a Python program, one can write certain statement to handle selected exceptions to print the error that is being raised. For instance, if you were to prompt a user with console input and the input is asking for an integer, but the user inserts a letter, this would raise an exception. If you were writing a program for this, most likely you would include a way to handle this exception because of the possibility of a user inserting a letter and not an integer.
Handling an Exception for ValueError:
1 2 3 4 5 6 | while True: try: x = int(input("What is your favorite number? ")) break except ValueError: print("Try again... That was not a valid number. ") |
Output:
1 2 3 | What is your favorite number? a Try again... That was not a valid number. What is your favorite number? 2 |
try statement break down
- The try clause, which is between the Python keywords; try and except
- If no exception occurs, the except statement is skipped and program completes
- If the exception occurs, the except statement is executed and prompting the user with incorrect input
- If an exception occurs which is outside of the ValueError exception, it will be passed on to outer try statements. However, if no handler is found, then it will prompt an unhandled exception.
The try statement allows more than one except clause when handling exceptions to specify certain exceptions. If you were to add three exceptions in the except clause, it would only execute one exception handler.
Also, if an exception has an argument, they can be printed to the except statement in detail for unhandled exception. These exception handlers can occur inside functions that are called and don’t only handle exceptions as they occur. Below is an example for earlier with:
ZeroDivisionError Except Statement
Input:
1 2 3 4 5 6 7 | def division_x(): x = 1/0 try: division_x() except ZeroDivisionError as err: print('Handling run-time error:', err) |
Output:
1 | Handling run-time error: division by zero |
How to Raise Exceptions
In Python, the raise statement allows the program to force a specified exception to occur.
raise NameError() Example
Input:
1 | >>> raise NameError("This is an example of raising an exception") |
Output:
1 2 3 4 | Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> raise NameError("This is an example of raising an exception") NameError: This is an example of raising an exception |
In order to raise an exception must be either instance of an exception or a class which derives from exception. If the exception class is passed, it will call the constructor with no arguments.
Input:
1 2 3 4 5 | try: raise NameError("This is an example of raising an exception") except NameError: print("Uh oh! An exception was passed!") raise |
Output:
1 2 3 4 5 | Uh oh! An exception was passed! Traceback (most recent call last): File "<pyshell#4>", line 2, in <module> raise NameError("This is an example of raising an exception") NameError: This is an example of raising an exception |
ValueError() and ZeroDivisionError Example
In the below try and except program, we created a list with a string, integers 0 and 2. The program will loop through the list until it matches a valid reciprocal. If no exception were to occur, the except block is skipped and moved to the next item in the list. We imported the sys library in Python and will use the ex_info to print out the exception type when the except block is executed with an exception for the item in the list.
In this program, we loop until the user enters an integer that has a valid reciprocal. The portion that can cause exception is placed inside try block.
If no exception occurs, except block is skipped and normal flow continues. But if any exception occurs, it is caught by the except block.
Here, we print the name of the exception using ex_info()
function inside sys
module and ask the user to try again. We can see that the values ‘a’ and ‘1.3’ causes ValueError and ‘0’ causes ZeroDivisionError.
Input:
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> import sys >>> listItems = ["c", 0, 2] >>> for entry in listItems: try: print(f"\nThe entry is {entry}") recip = 1/int(entry) break except: sysError = sys.exc_info()[0] print(f"Error: {sysError}") print("Next item in the list...") print(f"The reciprocal of {entry} is {recip}") |
Output:
1 2 3 4 5 6 7 8 9 10 | The entry is c Error: <class 'ValueError'> Next item in the list... The entry is 0 Error: <class 'ZeroDivisionError'> Next item in the list... The entry is 2 The reciprocal of 2 is 0.5 |
As you can see from the above, items “c” and 0 raise exceptions ValueError and ZeroDivisionError.