Python exception: try except with 3 examples to handle errors
Quick Reach
What is Python Exception?
The Exception is an object in Python that represents an error. As an error occurs in a program, Python generates an exception. To avoid crashing a program, this error should be handled.
Watch Video of Error handling Tutorial
This chapter explains how exceptions are handled by using Python try except statements.
An example of try except
How to raise an exception?
If you feel your code can produce an error, you can raise an exception in Python. In Python, raising an exception is quite simple. You can use raise exception statement that will break the current code execution and may return after it is handled.
Syntax of using try except
Following is the general structure of except with try statement:
Try:
Code lines to be executed
Except:
Error handler statements
Where the try block is the code of statements where you feel it can produce an error. It also allows to use multiple exception statements as explained in the section below.
An example of exception handling
In the example below, we will use a very basic program with variables a, b, c to demonstrate exception handling. Where a is an int variable, b is a string and c is the sum of a and b. Let us now check how interpreter gives the output:
The Output without try except block
See this example online
1 2 3 4 5 6 7 |
a = 10 b = 'xyz' c = (a + b) print (c) |
The output will be an error as follow:
Traceback (most recent call last):
File “C:\PythonPrograms\hello.py”, line 3, in <module>
c = (a + b)
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
Example with try and except
See this example online
1 2 3 4 5 6 7 8 9 10 11 12 13 |
try: a = 10 b = 'xyz' c = a + b print (c) except: print ("An error occurred") |
The output will be:
An error occurred
As you can see, the error is generated in both cases, as b is a string variable. With an exception handler, the error is more descriptive and the program is not crashed.
This can happen as you are taking input from the user, where you only accept numbers while user entered the strings. In that case, you can throw an error and show the user a descriptive error message without crashing the program.
An example of try except Python with user input
The following example takes the user input to generate an exception that is handled in the try-except block.
See this example online
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
try: a = int(input("Enter a number? ")) b = int(input("Enter another number? ")) c = (a + b) except ValueError: print ("Must enter an integer!") else: print ("Sum of two numbers = ", c) |
The output:
After running this code, the program will ask to enter two numbers. If 2 numbers are entered it will produce the sum of two. If a character is entered, an error will be generated that is handled in the error handler.
Python try except with else for multiple exceptions
You can use multiple exception handlers or try except blocks to manage more errors in the same program. First of all, you have to use a try block, followed by Exception handler 1, exception handler 2 and so on.
Finally, you can also place the else statement that will execute if no error occurs.
Following is the structure of multiple exception handling in Python.
Try:
Code lines to be executed
Except handler1:
Error handler statements
Except handler 2
Error handler statements
Else:
Execute if no exceptions here
Note that, the else block will be executed if no errors are generated.