[ Web Proxy ]
URL:
Viewing: https://www.pythontutorial.net/python-basics/python-try-except/ [Back]  [Original]

Python Try Except: How to Handle Exceptions More Gracefully
Skip to content

Python try…except

Summary: in this tutorial, you’ll learn how to use the Python try...except statement to handle exceptions gracefully.

In Python, there’re two main kinds of errors: syntax errors and exceptions.

Syntax errors #

When you write an invalid Python code, you’ll get a syntax error. For example:

current = 1
if current < 10
current += 1Copy

If you attempt to run this code, you’ll get the following error:

File "d:/python/try-except.py", line 2
    if current < 10
                  ^
SyntaxError: invalid syntaxCopy

In this example, the Python interpreter detected the error at the if statement since a colon (:) is missing after it.

The Python interpreter shows the file name and line number where the error occurred so that you can fix it.

Exceptions #

Even though when your code has valid syntax, it may cause an error during execution.

In Python, errors that occur during the execution are called exceptions. The causes of exceptions mainly come from the environment where the code executes. For example:

When an exception occurs, the program doesn’t handle it automatically. This results in an error message.

For example, the following program calculates the sales growth:

# get input net sales
print('Enter the net sales for')

previous = float(input('- Prior period:'))
current = float(input('- Current period:'))

# calculate the change in percentage
change = (current - previous) * 100 / previous

# show the result
if change > 0:
    result = f'Sales increase {abs(change)}%'
else:
    result = f'Sales decrease {abs(change)}%'

print(result)Copy

How it works.

When you run the program and enter 120' as the net sales of the current period, the Python interpreter will issue the following output:

Enter the net sales for
- Prior period:100
- Current period:120'
Traceback (most recent call last):
  File "d:/python/try-except.py", line 5, in <module>
    current = float(input('- Current period:'))
ValueError: could not convert string to float: "120'"Copy

The Python interpreter showed a traceback that includes detailed information of the exception:

Because float() couldn’t convert the string 120' to a number, the Python interpreter issued a ValueError exception.

In Python, exceptions have different types such as TypeError, NameError, etc.

Handling exceptions #

To make the program more robust, you need to handle the exception once it occurs. In other words, you need to catch the exception and inform users so that they can fix it.

A good way to handle this is not to show what the Python interpreter returns. Instead, you replace that error message with a more user-friendly one.

To do that, you can use the Python try...except statement:

try:
    # code that may cause error
except:
    # handle errorsCopy

The try...except statement works as follows:

The following flowchart illustrates the try...except statement:

So to handle exceptions using the try...except statement, you place the code that may cause an exception in the try clause and the code that handles exceptions in the except clause.

Here’s how you can rewrite the program and uses the try...except statement to handle the exception:

try:
    # get input net sales
    print('Enter the net sales for')

    previous = float(input('- Prior period:'))
    current = float(input('- Current period:'))

    # calculate the change in percentage
    change = (current - previous) * 100 / previous

    # show the result
    if change > 0:
        result = f'Sales increase {abs(change)}%'
    else:
        result = f'Sales decrease {abs(change)}%'

    print(result)
except:
    print('Error! Please enter a number for net sales.')
Copy

If you run the program again and enter the net sales which is not a number, the program will issue the message that you specified in the except block instead:

Enter the net sales for
- Prior period:100
- Current period:120'
Error! Please enter a number for net sales.Copy

Catching specific exceptions #

When you enter the net sales of the prior period as zero, you’ll get the following message:

Enter the net sales for
- Prior period:0
- Current period:100
Error! Please enter a number for net sales.Copy

In this case, both net sales of the prior and current periods are numbers, but the program still issues an error message. Another exception must occur.

The try...except statement allows you to handle a particular exception. To catch a selected exception, you place the type of exception after the except keyword:

try:
    # code that may cause an exception
except ValueError as error:
    # code to handle the exceptionCopy

For example:

try:
    # get input net sales
    print('Enter the net sales for')

    previous = float(input('- Prior period:'))
    current = float(input('- Current period:'))

    # calculate the change in percentage
    change = (current - previous) * 100 / previous

    # show the result
    if change > 0:
        result = f'Sales increase {abs(change)}%'
    else:
        result = f'Sales decrease {abs(change)}%'

    print(result)
except ValueError:
    print('Error! Please enter a number for net sales.')
Copy

When you run a program and enter a string for the net sales, you’ll get the same error message.

However, if you enter zero for the net sales of the prior period:

Enter the net sales for
- Prior period:0
- Current period:100Copy

… you’ll get the following error message:

Traceback (most recent call last):
  File "d:/python/try-except.py", line 9, in <module>
    change = (current - previous) * 100 / previous
ZeroDivisionError: float division by zeroCopy

This time you got the ZeroDivisionError exception. This division by zero exception is caused by the following statement:

change = (current - previous) * 100 / previousCopy

And the reason is that the value of the previous is zero.

Handling multiple exceptions #

The try...except allows you to handle multiple exceptions by specifying multiple except clauses:

try:
    # code that may cause an exception
except Exception1 as e1:
    # handle exception
except Exception2 as e2:
    # handle exception
except Exception3 as e3:
    # handle exception Copy

This allows you to respond to each type of exception differently.

If you want to have the same response to some types of exceptions, you can group them into one except clause:

try:
    # code that may cause an exception
except (Exception1, Exception2):
    # handle exceptionCopy

The following example shows how to use the try...except to handle the ValueError and ZeroDivisionError exceptions:

try:
    # get input net sales
    print('Enter the net sales for')

    previous = float(input('- Prior period:'))
    current = float(input('- Current period:'))

    # calculate the change in percentage
    change = (current - previous) * 100 / previous

    # show the result
    if change > 0:
        result = f'Sales increase {abs(change)}%'
    else:
        result = f'Sales decrease {abs(change)}%'

    print(result)
except ValueError:
    print('Error! Please enter a number for net sales.')
except ZeroDivisionError:
    print('Error! The prior net sales cannot be zero.')
Copy

When you enter zero for the net sales of the prior period:

Enter the net sales for
- Prior period:0
- Current period:120Copy

… you’ll get the following error:

Error! The prior net sales cannot be zero.Copy

It’s a good practice to catch other general errors by placing the catch Exception block at the end of the list:

try:
    # get input net sales
    print('Enter the net sales for')

    previous = float(input('- Prior period:'))
    current = float(input('- Current period:'))

    # calculate the change in percentage
    change = (current - previous) * 100 / previous

    # show the result
    if change > 0:
        result = f'Sales increase {abs(change)}%'
    else:
        result = f'Sales decrease {abs(change)}%'

    print(result)
except ValueError:
    print('Error! Please enter a number for net sales.')
except ZeroDivisionError:
    print('Error! The prior net sales cannot be zero.')
except Exception as error:
    print(error)Copy

Summary #

Quiz #

Quiz

try…except

8 questions

To help you understand how to use the Python try…except statement to handle exceptions gracefully.
Start quiz

Was this helpful?

YesNo

Getting Started

Python Fundamentals

Operators

Control Flow

Functions

Python List

Python Dictionary

Python Set

Exception Handling

Python Loop with Else Clause

More on Functions

Modules

File I/O

Directory

Managing Third-party Packages

Copyright © 2021 - Present, By Python Tutorial. All Rights Reserved.


Web Proxy Viewer  |  New URL  |  Original Page