- How Do I Convert an Exception to a String in Python
- How to Convert an Exception to a Python String?
- Method 1: Convert an Exceptions to a String in Python Using the “str()” Function
- Method 2: Convert an Exceptions to a String in Python Using “traceback.format_exc()” Function
- Method 3: Convert an Exceptions to a String in Python Using the “repr()” Function
- Conclusion
- About the author
- Talha Saif Malik
- Как преобразовать исключение в строку в Python?
- Пример 1
- Пример 2
- Заключение
How Do I Convert an Exception to a String in Python
An “exception” is a circumstance that disrupts the normal flow of instructions throughout the execution of a program. Python stops executing a program/code when an exception is thrown. If you’re a Python developer, you’ve probably run into errors or exceptions in your code. Python provides various methods to handle these exceptions with the “try-except” block. However, sometimes you may want to convert an exception to a string to get more information about the error.
In this Python article, we’ll explore the approaches to converting an exception to a Python string.
How to Convert an Exception to a Python String?
To convert an exception to a string, apply the following approaches:
Method 1: Convert an Exceptions to a String in Python Using the “str()” Function
The simplest way to convert an exception to a string is via the built-in “str()” function. This function accepts an object as an argument and retrieves a string representation of the object. It returns an error message when the exception object is passed as an argument.
Here, “object” is any Python object that can be converted to a string representation. The “str()” function returns a string object.
The following example illustrates the discussed concept:
try:
print ( 1 + ‘3’ )
except Exception as e:
error_message = str ( e )
print ( error_message )
print ( type ( error_message ) )
In the above code, the “TypeError” exception is caught by the “except” block. The “except” block assigns the exception object to the variable “e” and it is then passed to the “str()” function as an argument that converts it to a string.
In the above output, the exception has been converted into a string appropriately.
Method 2: Convert an Exceptions to a String in Python Using “traceback.format_exc()” Function
The “traceback.format_exc()” function of the “traceback” module can also be used to convert an exception to a string. This function returns a formatted traceback for the last exception that occurred. In the traceback, you will find/get the error message, the location where the error occurred, and the function call stack.
- The “limit (optional)” parameter indicates the number of stack levels to show for each exception in the traceback. The default value “None” means that all levels are shown.
- The “chain” parameter is optional and its default value is “true”. When set to “true”, the function prints the full traceback of the exception and all exceptions in the chain. Setting it to “false” prints only the traceback of the most recent exception.
As an example, let’s look at the following code snippet:
import traceback
try:
value = ‘Hello’
print ( int ( value ) )
except Exception as e:
error_message = traceback.format_exc ( )
print ( error_message )
print ( type ( error_message ) )
According to the above code, the “try-except” block is used to handle the exception and print the error message using the “traceback” module. The “traceback.format_exc()” function retrieves a string that contains the stack trace of the exception.
This outcome indicates that the exception has been successfully converted into a string.
Method 3: Convert an Exceptions to a String in Python Using the “repr()” Function
In Python, the “repr()” function is used to return a printable representation of an object in Python. This function can also be applied to convert an exception into a string.
In this syntax, “object” is any Python object whose printable representation needs to be returned.
Consider the following example code:
try:
value = ‘Hello’
print ( int ( value ) )
except Exception as e:
error_message = repr ( e )
print ( error_message )
print ( type ( error_message ) )
In the above code block, the “repr()” function is used in the “except” block to catch the faced exception and convert it into a string.
According to the above output, the faced exception has been converted into a string.
Conclusion
To convert an exception to a string in Python, apply the “str()” function, “traceback.format_exc()” function, or the “repr()” function. All of these functions are used combined with the “try-except” blocks to catch and convert the faced exception into a string. This guide presented various methods to convert an exception to a string in Python using numerous examples.
About the author
Talha Saif Malik
Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.
Как преобразовать исключение в строку в Python?
Программирование и разработка
Исключения, т.е. Ошибки, очень часто встречаются при программировании во время выполнения. Эти исключения могут быть вызваны некоторыми логическими ошибками, некоторыми проблемами синтаксиса или некоторыми проблемами конфигурации системы или программного обеспечения. Исключения могут привести к немедленному завершению работы вашей программы. Чтобы избежать этой быстрой остановки выполнения, мы использовали очень известный оператор try-catch. Есть еще один метод обработки таких исключений, чтобы вызвать остановку программы.
Итак, мы будем использовать преобразование в программе, чтобы преобразовать исключение в строку в Python. Убедитесь, что в вашей системе Linux есть конфигурация python3. Давайте начнем сначала с открытия консольного приложения, так как нам нужно работать с терминалом, используя Ctrl + Alt + T.
Пример 1
Итак, мы начали с создания нового файла Python в оболочке. Это было сделано с помощью «сенсорного» запроса в оболочке. После этого мы открывали файл с помощью редактора GNU Nano, чтобы создать в нем некоторый код Python. Обе команды указаны на изображении.
После открытия файла в редакторе мы использовали поддержку python3 в верхней строке, чтобы сделать его исполняемым. Сначала мы добавили простой код, чтобы увидеть, как возникает исключение в оболочке. Итак, мы инициализировали список «list» со значением 12. Список был увеличен на 5 с использованием оператора увеличения как «+ =» на следующей последовательной строке.
Использование ключевого слова python3 пакета Python для запуска нашего файла кода, то есть «convert.py». Взамен мы получили исключение, указывающее на исключение TypeError. В нем говорится, что целое число int не может повторяться в случае списков. Его необходимо использовать для некоторой переменной целочисленного типа. Результат выполнения сценария можно увидеть на прикрепленном изображении.
Вот как возникает исключение и останавливает выполнение любого программного кода в терминале оболочки системы Ubuntu 20.04. Давайте решим эту проблему, преобразовав исключение в строку, сделав ее отображаемой в оболочке как обычную строку и не допустив остановки выполнения. Итак, после открытия файла мы добавили поддержку python. Пока для этой цели будет использоваться оператор try-except.
В операторе try мы добавим наш код Python для выполнения и вызовем ошибку, т.е. инициализацию списка и его увеличение. Оператор except был использован здесь для получения ошибки исключения в переменной «e». Исключение будет преобразовано в строку, например str, и сохранено в переменной «строка». Строковая переменная будет напечатана в оболочке в конце. Сохраните обновленный код Python с помощью сочетания клавиш Ctrl + S.
#!/usr/bin/python3
Try:
list = [ 12 ]
list + = 5
except Exception as e:
string = str ( e )
print ( “The error is : ” , string )
У нас есть исключение в виде строки в оболочке, и программа не прекращает выполнение. Результат выполнения сценария можно увидеть на прикрепленном изображении.
Пример 2
Приведем еще один простой пример, чтобы поместить исключение в строку, чтобы предотвратить остановку программы. Мы запустили этот же файл в редакторе Nano и добавили поддержку python3. Оператор try содержит инициализацию списка с объединением его с целочисленным значением. Оператор except получает ошибку, преобразует ее в строку, сохраняет в переменной и распечатывает ее.
#!/usr/bin/python3
Try:
list = [ 12 ] + 1
except Exception as e:
string = str ( e )
print ( “Error: ” , string )
Мы получили ошибку «конкатенации» как результирующую строку в оболочке вместо ошибки. Результат выполнения сценария можно увидеть на прикрепленном изображении.
Заключение
В этой статье описана реализация преобразования исключения в строку и ее отображения в оболочке как обычного текста. Мы использовали два простых и легких примера Python, чтобы проиллюстрировать эту концепцию нашим пользователям. Мы очень надеемся и с нетерпением ждем ваших отзывов.