Python try except error code

In this beginner tutorial you'll learn what exceptions are good for in Python. You'll see how to raise exceptions and how to handle them with "try/except" blocks.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions

A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception. In this article, you will see what an exception is and how it differs from a syntax error. After that, you will learn about raising exceptions and making assertions. Then, you’ll finish with a demonstration of the try and except block.

An introduction to exceptions in Python

Exceptions versus Syntax Errors

Syntax errors occur when the parser detects an incorrect statement. Observe the following example:

>>> print( 0 / 0 ))
  File "<stdin>", line 1
    print( 0 / 0 ))
                  ^
SyntaxError: invalid syntax

The arrow indicates where the parser ran into the syntax error. In this example, there was one bracket too many. Remove it and run your code again:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into.

Instead of showing the message exception error, Python details what type of exception error was encountered. In this case, it was a ZeroDivisionError. Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions.

Raising an Exception

We can use raise to throw an exception if a condition occurs. The statement can be complemented with a custom exception.

Illustration of  raise statement usage

If you want to throw an error when a certain condition occurs using raise, you could go about it like this:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))

When you run this code, the output will be the following:

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10

The program comes to a halt and displays our exception to screen, offering clues about what went wrong.

The AssertionError Exception

Instead of waiting for a program to crash midway, you can also start by making an assertion in Python. We assert that a certain condition is met. If this condition turns out to be True, then that is excellent! The program can continue. If the condition turns out to be False, you can have the program throw an AssertionError exception.

Python assert statement

Have a look at the following example, where it is asserted that the code will be executed on a Linux system:

import sys
assert ('linux' in sys.platform), "This code runs on Linux only."

If you run this code on a Linux machine, the assertion passes. If you were to run this code on a Windows machine, the outcome of the assertion would be False and the result would be the following:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.

In this example, throwing an AssertionError exception is the last thing that the program will do. The program will come to halt and will not continue. What if that is not what you want?

The try and except Block: Handling Exceptions

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.

Diagram showing try and except statements

As you saw earlier, when syntactically correct code runs into an error, Python will throw an exception error. This exception error will crash the program if it is unhandled. The except clause determines how your program responds to exceptions.

The following function can help you understand the try and except block:

def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')

The linux_interaction() can only run on a Linux system. The assert in this function will throw an AssertionError exception if you call it on an operating system other then Linux.

You can give the function a try using the following code:

try:
    linux_interaction()
except:
    pass

The way you handled the error here is by handing out a pass. If you were to run this code on a Windows machine, you would get the following output:

You got nothing. The good thing here is that the program did not crash. But it would be nice to see if some type of exception occurred whenever you ran your code. To this end, you can change the pass into something that would generate an informative message, like so:

try:
    linux_interaction()
except:
    print('Linux function was not executed')

Execute this code on a Windows machine:

Linux function was not executed

When an exception occurs in a program running this function, the program will continue as well as inform you about the fact that the function call was not successful.

What you did not get to see was the type of error that was thrown as a result of the function call. In order to see exactly what went wrong, you would need to catch the error that the function threw.

The following code is an example where you capture the AssertionError and output that message to screen:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
    print('The linux_interaction() function was not executed')

Running this function on a Windows machine outputs the following:

Function can only run on Linux systems.
The linux_interaction() function was not executed

The first message is the AssertionError, informing you that the function can only be executed on a Linux machine. The second message tells you which function was not executed.

In the previous example, you called a function that you wrote yourself. When you executed the function, you caught the AssertionError exception and printed it to screen.

Here’s another example where you open a file and use a built-in exception:

try:
    with open('file.log') as file:
        read_data = file.read()
except:
    print('Could not open file.log')

If file.log does not exist, this block of code will output the following:

This is an informative message, and our program will still continue to run. In the Python docs, you can see that there are a lot of built-in exceptions that you can use here. One exception described on that page is the following:

Exception FileNotFoundError

Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.

To catch this type of exception and print it to screen, you could use the following code:

try:
    with open('file.log') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)

In this case, if file.log does not exist, the output will be the following:

[Errno 2] No such file or directory: 'file.log'

You can have more than one function call in your try clause and anticipate catching various exceptions. A thing to note here is that the code in the try clause will stop as soon as an exception is encountered.

Look at the following code. Here, you first call the linux_interaction() function and then try to open a file:

try:
    linux_interaction()
    with open('file.log') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)
except AssertionError as error:
    print(error)
    print('Linux linux_interaction() function was not executed')

If the file does not exist, running this code on a Windows machine will output the following:

Function can only run on Linux systems.
Linux linux_interaction() function was not executed

Inside the try clause, you ran into an exception immediately and did not get to the part where you attempt to open file.log. Now look at what happens when you run the code on a Linux machine:

[Errno 2] No such file or directory: 'file.log'

Here are the key takeaways:

  • A try clause is executed up until the point where the first exception is encountered.
  • Inside the except clause, or the exception handler, you determine how the program responds to the exception.
  • You can anticipate multiple exceptions and differentiate how the program should respond to them.
  • Avoid using bare except clauses.

The else Clause

In Python, using the else statement, you can instruct a program to execute a certain block of code only in the absence of exceptions.

Diagram of try, except, and else statements in Python

Look at the following example:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    print('Executing the else clause.')

If you were to run this code on a Linux system, the output would be the following:

Doing something.
Executing the else clause.

Because the program did not run into any exceptions, the else clause was executed.

You can also try to run code inside the else clause and catch possible exceptions there as well:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)

If you were to execute this code on a Linux machine, you would get the following result:

Doing something.
[Errno 2] No such file or directory: 'file.log'

From the output, you can see that the linux_interaction() function ran. Because no exceptions were encountered, an attempt to open file.log was made. That file did not exist, and instead of opening the file, you caught the FileNotFoundError exception.

Cleaning Up After Using finally

Imagine that you always had to implement some sort of action to clean up after executing your code. Python enables you to do so using the finally clause.

Diagram explaining try except else finally statements

Have a look at the following example:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('Cleaning up, irrespective of any exceptions.')

In the previous code, everything in the finally clause will be executed. It does not matter if you encounter an exception somewhere in the try or else clauses. Running the previous code on a Windows machine would output the following:

Function can only run on Linux systems.
Cleaning up, irrespective of any exceptions.

Summing Up

After seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. In this article, you saw the following options:

  • raise allows you to throw an exception at any time.
  • assert enables you to verify if a certain condition is met and throw an exception if it isn’t.
  • In the try clause, all statements are executed until an exception is encountered.
  • except is used to catch and handle the exception(s) that are encountered in the try clause.
  • else lets you code sections that should run only when no exceptions are encountered in the try clause.
  • finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.

Hopefully, this article helped you understand the basic tools that Python has to offer when dealing with exceptions.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions

При выполнении заданий к главам вы скорее всего нередко сталкивались с возникновением различных ошибок. На этой главе мы изучим подход, который позволяет обрабатывать ошибки после их возникновения.

Напишем программу, которая будет считать обратные значения для целых чисел из заданного диапазона и выводить их в одну строку с разделителем «;». Один из вариантов кода для решения этой задачи выглядит так:

print(";".join(str(1 / x) for x in range(int(input()), int(input()) + 1)))

Программа получилась в одну строчку за счёт использования списочных выражений. Однако при вводе диапазона чисел, включающем в себя 0 (например, от -1 до 1), программа выдаст следующую ошибку:

ZeroDivisionError: division by zero

В программе произошла ошибка «деление на ноль». Такая ошибка, возникающая при выполнении программы и останавливающая её работу, называется исключением.

Попробуем в нашей программе избавиться от возникновения исключения деления на ноль. Пусть при попадании 0 в диапазон чисел, обработка не производится и выводится сообщение «Диапазон чисел содержит 0». Для этого нужно проверить до списочного выражения наличие нуля в диапазоне:

interval = range(int(input()), int(input()) + 1)
if 0 in interval:
    print("Диапазон чисел содержит 0.")
else:
    print(";".join(str(1 / x) for x in interval))

Теперь для диапазона, включающего в себя 0, например, от -2 до 2, исключения ZeroDivisionError не возникнет. Однако при вводе строки, которую невозможно преобразовать в целое число (например, «a»), будет вызвано другое исключение:

ValueError: invalid literal for int() with base 10: 'a'

Произошло исключение ValueError. Для борьбы с этой ошибкой нам придётся проверить, что строка состоит только из цифр. Сделать это нужно до преобразования в число. Тогда наша программа будет выглядеть так:

start = input()
end = input()
# Метод lstrip("-"), удаляющий символы "-" в начале строки, нужен для учёта
# отрицательных чисел, иначе isdigit() вернёт для них False
if not (start.lstrip("-").isdigit() and end.lstrip("-").isdigit()):
    print("Необходимо ввести два числа.")
else:
    interval = range(int(start), int(end) + 1)
    if 0 in interval:
        print("Диапазон чисел содержит 0.")
    else:
        print(";".join(str(1 / x) for x in interval))

Теперь наша программа работает без ошибок и при вводе строк, которые нельзя преобразовать в целое число.

Подход, который был нами применён для предотвращения ошибок, называется «Look Before You Leap» (LBYL), или «посмотри перед прыжком». В программе, реализующей такой подход, проверяются возможные условия возникновения ошибок до исполнения основного кода.

Подход LBYL имеет недостатки. Программу из примера стало сложнее читать из-за вложенного условного оператора. Проверка условия, что строка может быть преобразована в число, выглядит даже сложнее, чем списочное выражение. Вложенный условный оператор не решает поставленную задачу, а только лишь проверяет входные данные на корректность. Легко заметить, что решение основной задачи заняло меньше времени, чем составление условий проверки корректности входных данных.

Существует другой подход для работы с ошибками: «Easier to Ask Forgiveness than Permission» (EAFP) или «проще извиниться, чем спрашивать разрешение». В этом подходе сначала исполняется код, а в случае возникновения ошибок происходит их обработка. Подход EAFP реализован в Python в виде обработки исключений.

Исключения в Python являются классами ошибок. В Python есть много стандартных исключений. Они имеют определённую иерархию за счёт механизма наследования классов. В документации Python версии 3.10.8 приводится следующее дерево иерархии стандартных исключений:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- EncodingWarning
           +-- ResourceWarning

Для обработки исключения в Python используется следующий синтаксис:

try:
    <код , который может вызвать исключения при выполнении>
except <классисключения_1>:
    <код обработки исключения>
except <классисключения_2>:
    <код обработки исключения>
...
else:
    <код выполняется, если не вызвано исключение в блоке try>
finally:
    <код , который выполняется всегда>

Блок try содержит код, в котором нужно обработать исключения, если они возникнут. При возникновении исключения интерпретатор последовательно проверяет в каком из блоков except обрабатывается это исключение. Исключение обрабатывается в первом блоке except, обрабатывающем класс этого исключения или базовый класс возникшего исключения. Необходимо учитывать иерархию исключений для определения порядка их обработки в блоках except. Начинать обработку исключений следует с более узких классов исключений. Если начать с более широкого класса исключения, например, Exception, то всегда при возникновении исключения будет срабатывать первый блок except. Сравните два следующих примера. В первом порядок обработки исключений указан от производных классов к базовым, а во втором – наоборот.

try:
    print(1 / int(input()))
except ZeroDivisionError:
    print("Ошибка деления на ноль.")
except ValueError:
    print("Невозможно преобразовать строку в число.")
except Exception:
    print("Неизвестная ошибка.")

При вводе значений «0» и «a» получим ожидаемый соответствующий возникающим исключениям вывод:

Невозможно преобразовать строку в число.

и

Ошибка деления на ноль.

Второй пример:

try:
    print(1 / int(input()))
except Exception:
    print("Неизвестная ошибка.")
except ZeroDivisionError:
    print("Ошибка деления на ноль.")
except ValueError:
    print("Невозможно преобразовать строку в число.")

При вводе значений «0» и «a» получим в обоих случаях неинформативный вывод:

Неизвестная ошибка.

Необязательный блок else выполняет код в случае, если в блоке try не вызвано исключение. Добавим блок else в пример для вывода сообщения об успешном выполнении операции:

try:
    print(1 / int(input()))
except ZeroDivisionError:
    print("Ошибка деления на ноль.")
except ValueError:
    print("Невозможно преобразовать строку в число.")
except Exception:
    print("Неизвестная ошибка.")
else:
    print("Операция выполнена успешно.")

Теперь при вводе корректного значения, например, «5», вывод программы будет следующим:

2.0
Операция выполнена успешно.

Блок finally выполняется всегда, даже если возникло какое-то исключение, не учтённое в блоках except или код в этих блоках сам вызвал какое-либо исключение. Добавим в нашу программу вывод строки «Программа завершена» в конце программы даже при возникновении исключений:

try:
    print(1 / int(input()))
except ZeroDivisionError:
    print("Ошибка деления на ноль.")
except ValueError:
    print("Невозможно преобразовать строку в число.")
except Exception:
    print("Неизвестная ошибка.")
else:
    print("Операция выполнена успешно.")
finally:
    print("Программа завершена.")

Перепишем код, созданный с применением подхода LBYL, для первого примера из этой главы с использованием обработки исключений:

try:
    print(";".join(str(1 / x) for x in range(int(input()), int(input()) + 1)))
except ZeroDivisionError:
    print("Диапазон чисел содержит 0.")
except ValueError:
    print("Необходимо ввести два числа.")

Теперь наша программа читается намного легче. При этом создание кода для обработки исключений не заняло много времени и не потребовало проверки сложных условий.

Исключения можно принудительно вызывать с помощью оператора raise. Этот оператор имеет следующий синтаксис:

raise <класс исключения>(параметры)

В качестве параметра можно, например, передать строку с сообщением об ошибке.

В Python можно создавать свои собственные исключения. Синтаксис создания исключения такой же, как и у создания класса. При создании исключения его необходимо наследовать от какого-либо стандартного класса-исключения.

Напишем программу, которая выводит сумму списка целых чисел, и вызывает исключение, если в списке чисел есть хотя бы одно чётное или отрицательное число. Создадим свои классы исключений:

  • NumbersError – базовый класс исключения;
  • EvenError – исключение, которое вызывается при наличии хотя бы одного чётного числа;
  • NegativeError – исключение, которое вызывается при наличии хотя бы одного отрицательного числа.
class NumbersError(Exception):
    pass


class EvenError(NumbersError):
    pass


class NegativeError(NumbersError):
    pass


def no_even(numbers):
    if all(x % 2 != 0 for x in numbers):
        return True
    raise EvenError("В списке не должно быть чётных чисел")


def no_negative(numbers):
    if all(x >= 0 for x in numbers):
        return True
    raise NegativeError("В списке не должно быть отрицательных чисел")


def main():
    print("Введите числа в одну строку через пробел:")
    try:
        numbers = [int(x) for x in input().split()]
        if no_negative(numbers) and no_even(numbers):
            print(f"Сумма чисел равна: {sum(numbers)}.")
    except NumbersError as e:  # обращение к исключению как к объекту
        print(f"Произошла ошибка: {e}.")
    except Exception as e:
        print(f"Произошла непредвиденная ошибка: {e}.")

        
if __name__ == "__main__":
    main()

Обратите внимание: в программе основной код выделен в функцию main. А код вне функций содержит только условный оператор и вызов функции main при выполнении условия __name__ == "__main__". Это условие проверяет, запущен ли файл как самостоятельная программа или импортирован как модуль.

Любая программа, написанная на языке программирования Python может быть импортирована как модуль в другую программу. В идеологии Python импортировать модуль – значит полностью его выполнить. Если основной код модуля содержит вызовы функций, ввод или вывод данных без использования указанного условия __name__ == "__main__", то произойдёт полноценный запуск программы. А это не всегда удобно, если из модуля нужна только отдельная функция или какой-либо класс.

При изучении модуля itertools, мы говорили о том, как импортировать модуль в программу. Покажем ещё раз два способа импорта на примере собственного модуля.

Для импорта модуля из файла, например example_module.py, нужно указать его имя, если он находится в той же папке, что и импортирующая его программа:

import example_module

Если требуется отдельный компонент модуля, например функция или класс, то импорт можно осуществить так:

from example_module import some_function, ExampleClass

Обратите внимание: при втором способе импортированные объекты попадают в пространство имён новой программы. Это означает, что они будут объектами новой программы, и в программе не должно быть других объектов с такими же именами.

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.
Note: For more information, refer to Errors and Exceptions in Python
Some of the common Exception Errors are : 
 

  • IOError: if the file can’t be opened
  • KeyboardInterrupt: when an unrequired key is pressed by the user
  • ValueError: when built-in function receives a wrong argument
  • EOFError: if End-Of-File is hit without reading any data
  • ImportError: if it is unable to find the module

Try Except in Python

Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.
 

Syntax: 

try:
    # Some Code
except:
    # Executed if error in the
    # try block

How try() works? 
 

  • First, the try clause is executed i.e. the code between try and except clause.
  • If there is no exception, then only the try clause will run, except the clause is finished.
  • If any exception occurs, the try clause will be skipped and except clause will run.
  • If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.
  • A try statement can have more than one except clause

Code 1: No exception, so the try clause will run. 
 

Python3

def divide(x, y):

    try:

        result = x // y

        print("Yeah ! Your answer is :", result)

    except ZeroDivisionError:

        print("Sorry ! You are dividing by zero ")

divide(3, 2)

Auxiliary Space: O(1)

Output : 
 

('Yeah ! Your answer is :', 1)

Code 1: There is an exception so only except clause will run. 
 

Python3

def divide(x, y):

    try:

        result = x // y

        print("Yeah ! Your answer is :", result)

    except ZeroDivisionError:

        print("Sorry ! You are dividing by zero ")

divide(3, 0)

Output : 
 

Sorry ! You are dividing by zero

Else Clause

In python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.
 

Syntax:

try:
    # Some Code
except:
    # Executed if error in the
    # try block
else:
    # execute if no exception

Code:

Python3

def AbyB(a , b):

    try:

        c = ((a+b) // (a-b))

    except ZeroDivisionError:

        print ("a/b result in 0")

    else:

        print (c)

AbyB(2.0, 3.0)

AbyB(3.0, 3.0)

Output:

-5.0
a/b result in 0

Finally Keyword in Python

Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after normal termination of try block or after try block terminates due to some exceptions.
 

Syntax:

try:
    # Some Code
except:
    # Executed if error in the
    # try block
else:
    # execute if no exception
finally:
    # Some code .....(always executed)

Code:

Python3

try:

    k = 5//0

    print(k)

except ZeroDivisionError:   

    print("Can't divide by zero")

finally:

    print('This is always executed'

Output:

Can't divide by zero
This is always executed

Related Articles: 
 

  • Output Questions
  • Exception Handling in Python
  • User-Defined Exceptions

This article is contributed by Mohit Gupta_OMG 😀. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Содержание:развернуть

  • Как устроен механизм исключений
  • Как обрабатывать исключения в Python (try except)
  • As — сохраняет ошибку в переменную

  • Finally — выполняется всегда

  • Else — выполняется когда исключение не было вызвано

  • Несколько блоков except

  • Несколько типов исключений в одном блоке except

  • Raise — самостоятельный вызов исключений

  • Как пропустить ошибку

  • Исключения в lambda функциях
  • 20 типов встроенных исключений в Python
  • Как создать свой тип Exception

Программа, написанная на языке Python, останавливается сразу как обнаружит ошибку. Ошибки могут быть (как минимум) двух типов:

  • Синтаксические ошибки — возникают, когда написанное выражение не соответствует правилам языка (например, написана лишняя скобка);
  • Исключения — возникают во время выполнения программы (например, при делении на ноль).

Синтаксические ошибки исправить просто (если вы используете IDE, он их подсветит). А вот с исключениями всё немного сложнее — не всегда при написании программы можно сказать возникнет или нет в данном месте исключение. Чтобы приложение продолжило работу при возникновении проблем, такие ошибки нужно перехватывать и обрабатывать с помощью блока try/except.

Как устроен механизм исключений

В Python есть встроенные исключения, которые появляются после того как приложение находит ошибку. В этом случае текущий процесс временно приостанавливается и передает ошибку на уровень вверх до тех пор, пока она не будет обработано. Если ошибка не будет обработана, программа прекратит свою работу (а в консоли мы увидим Traceback с подробным описанием ошибки).

💁‍♂️ Пример: напишем скрипт, в котором функция ожидает число, а мы передаём сроку (это вызовет исключение «TypeError»):

def b(value):
print("-> b")
print(value + 1) # ошибка тут

def a(value):
print("-> a")
b(value)

a("10")

> -> a
> -> b
> Traceback (most recent call last):
> File "test.py", line 11, in <module>
> a("10")
> File "test.py", line 8, in a
> b(value)
> File "test.py", line 3, in b
> print(value + 1)
> TypeError: can only concatenate str (not "int") to str

В данном примере мы запускаем файл «test.py» (через консоль). Вызывается функция «a«, внутри которой вызывается функция «b«. Все работает хорошо до сточки print(value + 1). Тут интерпретатор понимает, что нельзя конкатенировать строку с числом, останавливает выполнение программы и вызывает исключение «TypeError».

Далее ошибка передается по цепочке в обратном направлении: «b» → «a» → «test.py«. Так как в данном примере мы не позаботились обработать эту ошибку, вся информация по ошибке отобразится в консоли в виде Traceback.

Traceback (трассировка) — это отчёт, содержащий вызовы функций, выполненные в определенный момент. Трассировка помогает узнать, что пошло не так и в каком месте это произошло.

Traceback лучше читать снизу вверх ↑

Пример Traceback в Python

В нашем примере Traceback содержится следующую информацию (читаем снизу вверх):

  1. TypeError — тип ошибки (означает, что операция не может быть выполнена с переменной этого типа);
  2. can only concatenate str (not "int") to str — подробное описание ошибки (конкатенировать можно только строку со строкой);
  3. Стек вызова функций (1-я линия — место, 2-я линия — код). В нашем примере видно, что в файле «test.py» на 11-й линии был вызов функции «a» со строковым аргументом «10». Далее был вызов функции «b». print(value + 1) это последнее, что было выполнено — тут и произошла ошибка.
  4. most recent call last — означает, что самый последний вызов будет отображаться последним в стеке (в нашем примере последним выполнился print(value + 1)).

В Python ошибку можно перехватить, обработать, и продолжить выполнение программы — для этого используется конструкция try ... except ....

Как обрабатывать исключения в Python (try except)

В Python исключения обрабатываются с помощью блоков try/except. Для этого операция, которая может вызвать исключение, помещается внутрь блока try. А код, который должен быть выполнен при возникновении ошибки, находится внутри except.

Например, вот как можно обработать ошибку деления на ноль:

try:
a = 7 / 0
except:
print('Ошибка! Деление на 0')

Здесь в блоке try находится код a = 7 / 0 — при попытке его выполнить возникнет исключение и выполнится код в блоке except (то есть будет выведено сообщение «Ошибка! Деление на 0»). После этого программа продолжит свое выполнение.

💭 PEP 8 рекомендует, по возможности, указывать конкретный тип исключения после ключевого слова except (чтобы перехватывать и обрабатывать конкретные исключения):

try:
a = 7 / 0
except ZeroDivisionError:
print('Ошибка! Деление на 0')

Однако если вы хотите перехватывать все исключения, которые сигнализируют об ошибках программы, используйте тип исключения Exception:

try:
a = 7 / 0
except Exception:
print('Любая ошибка!')

As — сохраняет ошибку в переменную

Перехваченная ошибка представляет собой объект класса, унаследованного от «BaseException». С помощью ключевого слова as можно записать этот объект в переменную, чтобы обратиться к нему внутри блока except:

try:
file = open('ok123.txt', 'r')
except FileNotFoundError as e:
print(e)

> [Errno 2] No such file or directory: 'ok123.txt'

В примере выше мы обращаемся к объекту класса «FileNotFoundError» (при выводе на экран через print отобразится строка с полным описанием ошибки).

У каждого объекта есть поля, к которым можно обращаться (например если нужно логировать ошибку в собственном формате):

import datetime

now = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S")

try:
file = open('ok123.txt', 'r')
except FileNotFoundError as e:
print(f"{now} [FileNotFoundError]: {e.strerror}, filename: {e.filename}")

> 20-11-2021 18:42:01 [FileNotFoundError]: No such file or directory, filename: ok123.txt

Finally — выполняется всегда

При обработке исключений можно после блока try использовать блок finally. Он похож на блок except, но команды, написанные внутри него, выполняются обязательно. Если в блоке try не возникнет исключения, то блок finally выполнится так же, как и при наличии ошибки, и программа возобновит свою работу.

Обычно try/except используется для перехвата исключений и восстановления нормальной работы приложения, а try/finally для того, чтобы гарантировать выполнение определенных действий (например, для закрытия внешних ресурсов, таких как ранее открытые файлы).

В следующем примере откроем файл и обратимся к несуществующей строке:

file = open('ok.txt', 'r')

try:
lines = file.readlines()
print(lines[5])
finally:
file.close()
if file.closed:
print("файл закрыт!")

> файл закрыт!
> Traceback (most recent call last):
> File "test.py", line 5, in <module>
> print(lines[5])
> IndexError: list index out of range

Даже после исключения «IndexError», сработал код в секции finally, который закрыл файл.

p.s. данный пример создан для демонстрации, в реальном проекте для работы с файлами лучше использовать менеджер контекста with.

Также можно использовать одновременно три блока try/except/finally. В этом случае:

  • в try — код, который может вызвать исключения;
  • в except — код, который должен выполниться при возникновении исключения;
  • в finally — код, который должен выполниться в любом случае.

def sum(a, b):
res = 0

try:
res = a + b
except TypeError:
res = int(a) + int(b)
finally:
print(f"a = {a}, b = {b}, res = {res}")

sum(1, "2")

> a = 1, b = 2, res = 3

Else — выполняется когда исключение не было вызвано

Иногда нужно выполнить определенные действия, когда код внутри блока try не вызвал исключения. Для этого используется блок else.

Допустим нужно вывести результат деления двух чисел и обработать исключения в случае попытки деления на ноль:

b = int(input('b = '))
c = int(input('c = '))
try:
a = b / c
except ZeroDivisionError:
print('Ошибка! Деление на 0')
else:
print(f"a = {a}")

> b = 10
> c = 1
> a = 10.0

В этом случае, если пользователь присвоит переменной «с» ноль, то появится исключение и будет выведено сообщение «‘Ошибка! Деление на 0′», а код внутри блока else выполняться не будет. Если ошибки не будет, то на экране появятся результаты деления.

Несколько блоков except

В программе может возникнуть несколько исключений, например:

  1. Ошибка преобразования введенных значений к типу float («ValueError»);
  2. Деление на ноль («ZeroDivisionError»).

В Python, чтобы по-разному обрабатывать разные типы ошибок, создают несколько блоков except:

try:
b = float(input('b = '))
c = float(input('c = '))
a = b / c
except ZeroDivisionError:
print('Ошибка! Деление на 0')
except ValueError:
print('Число введено неверно')
else:
print(f"a = {a}")

> b = 10
> c = 0
> Ошибка! Деление на 0

> b = 10
> c = питон
> Число введено неверно

Теперь для разных типов ошибок есть свой обработчик.

Несколько типов исключений в одном блоке except

Можно также обрабатывать в одном блоке except сразу несколько исключений. Для этого они записываются в круглых скобках, через запятую сразу после ключевого слова except. Чтобы обработать сообщения «ZeroDivisionError» и «ValueError» в одном блоке записываем их следующим образом:

try:
b = float(input('b = '))
c = float(input('c = '))
a = b / c
except (ZeroDivisionError, ValueError) as er:
print(er)
else:
print('a = ', a)

При этом переменной er присваивается объект того исключения, которое было вызвано. В результате на экран выводятся сведения о конкретной ошибке.

Raise — самостоятельный вызов исключений

Исключения можно генерировать самостоятельно — для этого нужно запустить оператор raise.

min = 100
if min > 10:
raise Exception('min must be less than 10')

> Traceback (most recent call last):
> File "test.py", line 3, in <module>
> raise Exception('min value must be less than 10')
> Exception: min must be less than 10

Перехватываются такие сообщения точно так же, как и остальные:

min = 100

try:
if min > 10:
raise Exception('min must be less than 10')
except Exception:
print('Моя ошибка')

> Моя ошибка

Кроме того, ошибку можно обработать в блоке except и пробросить дальше (вверх по стеку) с помощью raise:

min = 100

try:
if min > 10:
raise Exception('min must be less than 10')
except Exception:
print('Моя ошибка')
raise

> Моя ошибка
> Traceback (most recent call last):
> File "test.py", line 5, in <module>
> raise Exception('min must be less than 10')
> Exception: min must be less than 10

Как пропустить ошибку

Иногда ошибку обрабатывать не нужно. В этом случае ее можно пропустить с помощью pass:

try:
a = 7 / 0
except ZeroDivisionError:
pass

Исключения в lambda функциях

Обрабатывать исключения внутри lambda функций нельзя (так как lambda записывается в виде одного выражения). В этом случае нужно использовать именованную функцию.

20 типов встроенных исключений в Python

Иерархия классов для встроенных исключений в Python выглядит так:

BaseException
SystemExit
KeyboardInterrupt
GeneratorExit
Exception
ArithmeticError
AssertionError
...
...
...
ValueError
Warning

Все исключения в Python наследуются от базового BaseException:

  • SystemExit — системное исключение, вызываемое функцией sys.exit() во время выхода из приложения;
  • KeyboardInterrupt — возникает при завершении программы пользователем (чаще всего при нажатии клавиш Ctrl+C);
  • GeneratorExit — вызывается методом close объекта generator;
  • Exception — исключения, которые можно и нужно обрабатывать (предыдущие были системными и их трогать не рекомендуется).

От Exception наследуются:

1 StopIteration — вызывается функцией next в том случае если в итераторе закончились элементы;

2 ArithmeticError — ошибки, возникающие при вычислении, бывают следующие типы:

  • FloatingPointError — ошибки при выполнении вычислений с плавающей точкой (встречаются редко);
  • OverflowError — результат вычислений большой для текущего представления (не появляется при операциях с целыми числами, но может появиться в некоторых других случаях);
  • ZeroDivisionError — возникает при попытке деления на ноль.

3 AssertionError — выражение, используемое в функции assert неверно;

4 AttributeError — у объекта отсутствует нужный атрибут;

5 BufferError — операция, для выполнения которой требуется буфер, не выполнена;

6 EOFError — ошибка чтения из файла;

7 ImportError — ошибка импортирования модуля;

8 LookupError — неверный индекс, делится на два типа:

  • IndexError — индекс выходит за пределы диапазона элементов;
  • KeyError — индекс отсутствует (для словарей, множеств и подобных объектов);

9 MemoryError — память переполнена;

10 NameError — отсутствует переменная с данным именем;

11 OSError — исключения, генерируемые операционной системой:

  • ChildProcessError — ошибки, связанные с выполнением дочернего процесса;
  • ConnectionError — исключения связанные с подключениями (BrokenPipeError, ConnectionResetError, ConnectionRefusedError, ConnectionAbortedError);
  • FileExistsError — возникает при попытке создания уже существующего файла или директории;
  • FileNotFoundError — генерируется при попытке обращения к несуществующему файлу;
  • InterruptedError — возникает в том случае если системный вызов был прерван внешним сигналом;
  • IsADirectoryError — программа обращается к файлу, а это директория;
  • NotADirectoryError — приложение обращается к директории, а это файл;
  • PermissionError — прав доступа недостаточно для выполнения операции;
  • ProcessLookupError — процесс, к которому обращается приложение не запущен или отсутствует;
  • TimeoutError — время ожидания истекло;

12 ReferenceError — попытка доступа к объекту с помощью слабой ссылки, когда объект не существует;

13 RuntimeError — генерируется в случае, когда исключение не может быть классифицировано или не подпадает под любую другую категорию;

14 NotImplementedError — абстрактные методы класса нуждаются в переопределении;

15 SyntaxError — ошибка синтаксиса;

16 SystemError — сигнализирует о внутренне ошибке;

17 TypeError — операция не может быть выполнена с переменной этого типа;

18 ValueError — возникает когда в функцию передается объект правильного типа, но имеющий некорректное значение;

19 UnicodeError — исключение связанное с кодирование текста в unicode, бывает трех видов:

  • UnicodeEncodeError — ошибка кодирования;
  • UnicodeDecodeError — ошибка декодирования;
  • UnicodeTranslateError — ошибка перевода unicode.

20 Warning — предупреждение, некритическая ошибка.

💭 Посмотреть всю цепочку наследования конкретного типа исключения можно с помощью модуля inspect:

import inspect

print(inspect.getmro(TimeoutError))

> (<class 'TimeoutError'>, <class 'OSError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>)

📄 Подробное описание всех классов встроенных исключений в Python смотрите в официальной документации.

Как создать свой тип Exception

В Python можно создавать свои исключения. При этом есть одно обязательное условие: они должны быть потомками класса Exception:

class MyError(Exception):
def __init__(self, text):
self.txt = text

try:
raise MyError('Моя ошибка')
except MyError as er:
print(er)

> Моя ошибка


С помощью try/except контролируются и обрабатываются ошибки в приложении. Это особенно актуально для критически важных частей программы, где любые «падения» недопустимы (или могут привести к негативным последствиям). Например, если программа работает как «демон», падение приведет к полной остановке её работы. Или, например, при временном сбое соединения с базой данных, программа также прервёт своё выполнение (хотя можно было отловить ошибку и попробовать соединиться в БД заново).

Вместе с try/except можно использовать дополнительные блоки. Если использовать все блоки описанные в статье, то код будет выглядеть так:

try:
# попробуем что-то сделать
except (ZeroDivisionError, ValueError) as e:
# обрабатываем исключения типа ZeroDivisionError или ValueError
except Exception as e:
# исключение не ZeroDivisionError и не ValueError
# поэтому обрабатываем исключение общего типа (унаследованное от Exception)
# сюда не сходят исключения типа GeneratorExit, KeyboardInterrupt, SystemExit
else:
# этот блок выполняется, если нет исключений
# если в этом блоке сделать return, он не будет вызван, пока не выполнился блок finally
finally:
# этот блок выполняется всегда, даже если нет исключений else будет проигнорирован
# если в этом блоке сделать return, то return в блоке

Подробнее о работе с исключениями в Python можно ознакомиться в официальной документации.

The try except statement can handle exceptions. Exceptions may happen when you run a program.

Exceptions are errors that happen during execution of the program. Python won’t tell you about errors like syntax errors (grammar faults), instead it will abruptly stop.

An abrupt exit is bad for both the end user and developer.

Instead of an emergency halt, you can use a try except statement to properly deal with the problem. An emergency halt will happen if you do not properly handle exceptions.

Related course: Complete Python Programming Course & Exercises

What are exceptions in Python?

Python has built-in exceptions which can output an error. If an error occurs while running the program, it’s called an exception.

If an exception occurs, the type of exception is shown. Exceptions needs to be dealt with or the program will crash. To handle exceptions, the try-catch block is used.

Some exceptions you may have seen before are FileNotFoundError, ZeroDivisionError or ImportError but there are many more.

All exceptions in Python inherit from the class BaseException. If you open the Python interactive shell and type the following statement it will list all built-in exceptions:

The idea of the try-except clause is to handle exceptions (errors at runtime). The syntax of the try-except block is:

1
2
3
4
try:
<do something>
except Exception:
<handle the error>

The idea of the try-except block is this:

  • try: the code with the exception(s) to catch. If an exception is raised, it jumps straight into the except block.

  • except: this code is only executed if an exception occured in the try block. The except block is required with a try block, even if it contains only the pass statement.

It may be combined with the else and finally keywords.

  • else: Code in the else block is only executed if no exceptions were raised in the try block.

  • finally: The code in the finally block is always executed, regardless of if a an exception was raised or not.

Catching Exceptions in Python

The try-except block can handle exceptions. This prevents abrupt exits of the program on error. In the example below we purposely raise an exception.

1
2
3
4
5
6
try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')

After the except block, the program continues. Without a try-except block, the last line wouldn’t be reached as the program would crash.

 $ python3 example.py

Divided by zero
Should reach here

In the above example we catch the specific exception ZeroDivisionError. You can handle any exception like this:

1
2
3
4
5
6
try: 
open("fantasy.txt")
except:
print('Something went wrong')

print('Should reach here')

You can write different logic for each type of exception that happens:

1
2
3
4
5
6
7
8
9
10
try: 

except FileNotFoundError:

except IsADirectoryError:

except:


print('Should reach here')

Related course: Complete Python Programming Course & Exercises

try-except

Lets take do a real world example of the try-except block.

The program asks for numeric user input. Instead the user types characters in the input box. The program normally would crash. But with a try-except block it can be handled properly.

The try except statement prevents the program from crashing and properly deals with it.

1
2
3
4
5
6
try:
x = input("Enter number: ")
x = x + 1
print(x)
except:
print("Invalid input")

Entering invalid input, makes the program continue normally:

try except

The try except statement can be extended with the finally keyword, this will be executed if no exception is thrown:

1
2
finally:
print("Valid input.")

The program continues execution if no exception has been thrown.

There are different kinds of exceptions: ZeroDivisionError, NameError, TypeError and so on. Sometimes modules define their own exceptions.

The try-except block works for function calls too:

1
2
3
4
5
6
7
8
9
def fail():
1 / 0

try:
fail()
except:
print('Exception occured')

print('Program continues')

This outputs:

 $ python3 example.py

Exception occured
Program continues

If you are a beginner, then I highly recommend this book.

try finally

A try-except block can have the finally clause (optionally). The finally clause is always executed.
So the general idea is:

1
2
3
4
5
6
try:
<do something>
except Exception:
<handle the error>
finally:
<cleanup>

For instance: if you open a file you’ll want to close it, you can do so in the finally clause.

1
2
3
4
5
6
7
8
try: 
f = open("test.txt")
except:
print('Could not open file')
finally:
f.close()

print('Program continue')

try else

The else clause is executed if and only if no exception is raised. This is different from the finally clause that’s always executed.

1
2
3
4
5
6
7
8
try:
x = 1
except:
print('Failed to set x')
else:
print('No exception occured')
finally:
print('We always do this')

Output:

 No exception occured
We always do this

You can catch many types of exceptions this way, where the else clause is executed only if no exception happens.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try:
lunch()
except SyntaxError:
print('Fix your syntax')
except TypeError:
print('Oh no! A TypeError has occured')
except ValueError:
print('A ValueError occured!')
except ZeroDivisionError:
print('Did by zero?')
else:
print('No exception')
finally:
print('Ok then')

Raise Exception

Exceptions are raised when an error occurs. But in Python you can also force an exception to occur with the keyword raise.

Any type of exception can be raised:

1
2
3
4
>>> raise MemoryError("Out of memory")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError: Out of memory
1
2
3
4
5
>>> raise ValueError("Wrong value")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Wrong value
>>>

Related course: Complete Python Programming Course & Exercises

Built-in exceptions

A list of Python’s Built-in Exceptions is shown below. This list shows the Exception and why it is thrown (raised).

Exception Cause of Error
AssertionError if assert statement fails.
AttributeError if attribute assignment or reference fails.
EOFError if the input() functions hits end-of-file condition.
FloatingPointError if a floating point operation fails.
GeneratorExit Raise if a generator’s close() method is called.
ImportError if the imported module is not found.
IndexError if index of a sequence is out of range.
KeyError if a key is not found in a dictionary.
KeyboardInterrupt if the user hits interrupt key (Ctrl+c or delete).
MemoryError if an operation runs out of memory.
NameError if a variable is not found in local or global scope.
NotImplementedError by abstract methods.
OSError if system operation causes system related error.
OverflowError if result of an arithmetic operation is too large to be represented.
ReferenceError if a weak reference proxy is used to access a garbage collected referent.
RuntimeError if an error does not fall under any other category.
StopIteration by next() function to indicate that there is no further item to be returned by iterator.
SyntaxError by parser if syntax error is encountered.
IndentationError if there is incorrect indentation.
TabError if indentation consists of inconsistent tabs and spaces.
SystemError if interpreter detects internal error.
SystemExit by sys.exit() function.
TypeError if a function or operation is applied to an object of incorrect type.
UnboundLocalError if a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeError if a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError if a Unicode-related error occurs during encoding.
UnicodeDecodeError if a Unicode-related error occurs during decoding.
UnicodeTranslateError if a Unicode-related error occurs during translating.
ValueError if a function gets argument of correct type but improper value.
ZeroDivisionError if second operand of division or modulo operation is zero.

User-defined Exceptions

Python has many standard types of exceptions, but they may not always serve your purpose.
Your program can have your own type of exceptions.

To create a user-defined exception, you have to create a class that inherits from Exception.

1
2
3
4
class LunchError(Exception):
pass

raise LunchError("Programmer went to lunch")

You made a user-defined exception named LunchError in the above code. You can raise this new exception if an error occurs.

Outputs your custom error:

 $ python3 example.py
Traceback (most recent call last):
File “example.py”, line 5, in
raise LunchError(“Programmer went to lunch”)
main.LunchError: Programmer went to lunch

Your program can have many user-defined exceptions. The program below throws exceptions based on a new projects money:

1
2
3
4
5
6
7
8
9
10
11
class NoMoneyException(Exception):
pass

class OutOfBudget(Exception):
pass

balance = int(input("Enter a balance: "))
if balance < 1000:
raise NoMoneyException
elif balance > 10000:
raise OutOfBudget

Here are some sample runs:

 $ python3 example.py
Enter a balance: 500
Traceback (most recent call last):
File “example.py”, line 10, in
raise NoMoneyException
main.NoMoneyException
 $ python3 example.py
$ python3 example.py
Enter a balance: 100000
Traceback (most recent call last):
File “example.py”, line 12, in
raise OutOfBudget
main.OutOfBudget

It is a good practice to put all user-defined exceptions in a separate file (exceptions.py or errors.py). This is common practice in standard modules too.

If you are a beginner, then I highly recommend this book.

Exercises

  1. Can try-except be used to catch invalid keyboard input?
  2. Can try-except catch the error if a file can’t be opened?
  3. When would you not use try-except?

Download examples

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 += 1

Code language: Python (python)

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 syntax

Code language: Shell Session (shell)

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.

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:

  • Reading a file that doesn’t exist.
  • Connecting to a remote server that is offline.
  • Bad user inputs.

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)

Code language: Python (python)

How it works.

  • First, prompt users for entering two numbers: the net sales of the prior and current periods.
  • Then, calculate the sales growth in percentage and show the result.

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'"

Code language: Shell Session (shell)

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

  • The path to the source code file (d:/python/try-except.py) that caused the exception.
  • The exact line of code that caused the exception (line 5)
  • The statement that caused the exception current = float(input('- Current period:'))
  • The type of exception ValueError
  • The error message: ValueError: could not convert string to float: "120'"

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 errors

Code language: Python (python)

The try...except statement works as follows:

  • The statements in the try clause execute first.
  • If no exception occurs, the except clause is skipped and the execution of the try statement is completed.
  • If an exception occurs at any statement in the try clause, the rest of the clause is skipped and the except clause is executed.

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

Python try...except

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.')

Code language: Python (python)

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.

Code language: Shell Session (shell)

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.

Code language: Shell Session (shell)

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 exception

Code language: Python (python)

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.')

Code language: Python (python)

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:100

Code language: Shell Session (shell)

… 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 zero

Code language: Shell Session (shell)

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

change = (current - previous) * 100 / previous

Code language: Python (python)

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

Code language: Python (python)

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 exception

Code language: Python (python)

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.')

Code language: Python (python)

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

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

Code language: Shell Session (shell)

… you’ll get the following error:

Error! The prior net sales cannot be zero.

Code language: Shell Session (shell)

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)

Code language: Python (python)

Summary

  • Use Python try...except statement to handle exceptions gracefully.
  • Use specific exceptions in the except block as much as possible.
  • Use the except Exception statement to catch other exceptions.

Did you find this tutorial helpful ?

Понравилась статья? Поделить с друзьями:
  • Python try except any error
  • Python tkinter окно ошибки
  • Python throw error
  • Python tab space error
  • Python systemerror error return without exception set