Как получить имя ошибки python

When you say «name» this could mean a couple of things: it could mean only the «immediate» classname, or it could mean the fully qualified name. Usually the latter will be much more useful and less error-prone: I’ve come across more than one case of 2 or more types with same «immediate» classname but from different packages.

If you want to print or log the fully qualified name this is one of the simplest things to do:

try:
    do_something()
except BaseException as e:
    logger.error(f'whoops! {type(e)}: {e}')
    # or maybe
    print(f'whoops! {type(e)}: {e}', file=sys.stderr)

The fully qualified classname will then be printed out like this: «<class ‘json.decoder.JSONDecodeError’>», and then be followed by the exception message. The OP says he wants «for example», to print a message, so assert statements as in the chosen answer don’t seem to be called for.

The answer by MrName is also not irrelevant, and does make a sensible suggestion! if in the above you replaced logger.error(...) with logger.exception('whoops!') (NB a user message is a required param) you’d get your exception’s fully qualified name logged, not to mention its message, and a stack trace for free.

PS as suggested by the name, JSONDecodeError in my example is an Error, not an Exception (it is a subclass of ValueError). Catching BaseException (the superclass of both Error and Exception) usually makes life easier when you’re not fishing for a specific exception. The OP says he wants to catch «all» exceptions.

How to get the name of an exception that was caught in Python

Ссылка на оверфло

Три варианта:

  • type(exception).__name__
  • exception.__class__.__name__
  • exception.__class__.__qualname__

Пример реализации

try:
    foo = bar
except Exception as exception:
    assert type(exception).__name__ == 'NameError'
    assert exception.__class__.__name__ == 'NameError'
    assert exception.__class__.__qualname__ == 'NameError'

Смотри в дополнение про то, как получить сообщение ошибки в виде строки [2021-06-04-daily-note]

Feature Launch: Import scripts into notebook kernels

Скажем так, не сильно полезная фича, т.к. нет возможности выстроить настоящую структуру пакета, а импорт ограничивается ноутом. Ну и плюс все это надо делать руками через jupyter notebook. Но, если есть какие-то сильно часто встречающиеся куски кода, то можно попробовать так реализовать.

  • Create a script kernel with the code you’d like to import.
  • Under the “File” menu, click on “Make Utility Script”. This will let you import this script to notebook kernels.
  • Commit your script. When you import a script, you’re importing the most recent committed version. If you haven’t committed a version yet, you won’t see it in the list of scripts you can import.
  • Open the notebook where you’d like to import the script.
  • Add the script. Under “File”, click “Add utility script”. Search for the script you want and click to add it. You should see it listed under “usr/lib” in the panel on the right hand side.
  • Import your script. In Python you can do this using import nameof_script.
  • Use the functions or objects you’ve imported!

  • a utility script can be a combination of multiple code snippets in different source files
  • be able to add data/non-code related files as part of the utility function
  • allow folder structure where code and data can reside in a structured fashion
  • allow access to the data area of the notebook via an environment variable or some other method
  • allow linking a gist where the code can reside (gist will contain the code for the utility script)
  • allow linking a git repo (via branch or commit points) — will contain the code for the utility script)
  • allow linking only a folder in a git repo where the code and data resides

The above will help in the following ways:

  • keep the main utility script small, simple and modular
  • easy to read, change and use
  • can be version controlled via another public SCM system while still visible to the kernel
  • keep components of the utility script separate from the data or configuration files in an organised manner

Какое-то там обсуждение на эту тему

In this Python Tutorial let us learn about the 3 different pieces of information that you can extract and use from the Exceptions caught on your except clauses, and see the best ways to use each of these pieces in our Python programs.

Let us start by learning what the 3 pieces of information are.

What kind of information can you get from Exceptions?

You can get the following 3 pieces of data from exceptions

  • Exception Type,
  • Exception Value a.k.a Error Message, and
  • Stack-trace or Traceback Object.

All three of the above information is printed out by the Python Interpreter when our program crashes due to an exception as shown in the following example

>> my_list = [1,2]
>> print (my_list[3])
Traceback (most recent call last):

  File "<ipython-input-35-63c7f9106be5>", line 1, in <module>
    print (my_list[3])

IndexError: list index out of range

Lines 3,4,5,6 shows the Stack-trace
Line 7 shows the Exception type and Error Message.

Our focus in this article is to learn how to extract the above 3 pieces individually in our except clauses and print them out as needed.

Hence, the rest of the article is all about answering the following questions

  • what does each of the information in the above list mean,
  • how to extract each of these 3 pieces individually and
  • how to use these pieces in our programs.

Piece#1: Printing Exception Type

The Exception Type refers to the class to which the Exception that you have just caught belongs to.

Extracting Piece#1 (Exception Type)

Let us improve our Example 1 above by putting the problematic code into try and except clauses.

try:
  my_list = [1,2]
  print (my_list[3])
except Exception as e:
  print(type(e))

Here, in the try clause, we have declared a List named my_list and initialized the list with 2 items. Then we have tried to print the 3rd/non-existent item in the list.

The except clause catches the IndexError exception and prints out Exception type.

On running the code, we will get the following output

<class 'IndexError'>

As you can see we just extracted and printed out the information about the class to which the exception that we have just caught belongs to!

But how exactly did we do that?
If you have a look at the except clause. In the line

except Exception as e:

what we have done is, we have assigned the caught exception to an object named “e”. Then by using the built-in python function type(), we have printed out the class name that the object e belongs to.

print(type(e))

Where to get more details about Exception Types

Now that we have the “Exception Type”, next we will probably need to get some information about that particular type so that we can get a better understanding of why our code has failed. In order to do that, the best place to start is the official documentation.

For built in exceptions you can have a look at the Python Documentation

For Exception types that come with the libraries that you use with your code, refer to the documentation of your library.

Piece#2: Printing Exception Value a.k.a Error message

The Exception type is definitely useful for debugging, but, a message like IndexError might sound cryptic and a good understandable error-message will make our job of debugging easier without having to look at the documentation.

In other words, if your program is to be run on the command line and you wish to log why the program just crashed then it is better to use an “Error message” rather than an “Exception Type”.

The example below shows how to print such an Error message.

try:
  my_list = [1,2]
  print (my_list[3])
except Exception as e:
  print(e)

This will print the default error message as follows

list index out of range

Each Exception type comes with its own error message. This can be retrieved using the built-in function print().

Say your program is going to be run by a not-so-tech-savvy user, in that case, you might want to print something friendlier. You can do so by passing in the string to be printed along with the constructor as follows.

try:
  raise IndexError('Custom message about IndexError')
except Exception as e:
  print(e)

This will print

Custom message about IndexError

To understand how the built-in function print() does this magic, and see some more examples of manipulating these error messages, I recommend reading my other article in the link below.

Python Exception Tutorial: Printing Error Messages (5 Examples!)

If you wish to print both the Error message and the Exception type, which I recommend, you can do so like below.

try:
  my_list = [1,2]
  print (my_list[3])
except Exception as e:
  print(repr(e))

This will print something like

IndexError('list index out of range')

Now that we have understood how to get control over the usage of Pieces 1 and 2, let us go ahead and look at the last and most important piece for debugging, the stack-trace which tells us where exactly in our program have the Exception occurred.

Piece#3: Printing/Logging the stack-trace using the traceback object

Stack-trace in Python is packed into an object named traceback object.

This is an interesting one as the traceback class in Python comes with several useful methods to exercise complete control over what is printed.

Let us see how to use these options using some examples!

import traceback

try:
  my_list = [1,2]
  print (my_list[3])
except Exception:
  traceback.print_exc()

This will print something like

Traceback (most recent call last):
  File "<ipython-input-38-f9a1ee2cf77a>", line 5, in <module>
    print (my_list[3])
IndexError: list index out of range

which contains the entire error messages printed by the Python interpreter if we fail to handle the exception.

Here, instead of crashing the program, we have printed this entire message using our exception handler with the help of the print_exc() method of the traceback class.

The above Example-6 is too simple, as, in the real-world, we will normally have several nested function calls which will result in a deeper stack. Let us see an example of how to control the output in such situations.

def func3():
  my_list = [1,2]
  print (my_list[3])

def func2():
  print('calling func3')
  func3()

def func1():
  print('calling func2')
  func2()

try:
  print('calling func1')
  func1()
except Exception as e:
    traceback.print_exc()

Here in the try clause we call func1(), which in-turn calls func2(), which in-turn calls func3(), which produces an IndexError. Running the code above we get the following output

calling func1
calling func2
calling func3
Traceback (most recent call last):
  File "<ipython-input-42-2267707e164f>", line 15, in <module>
    func1()
  File "<ipython-input-42-2267707e164f>", line 11, in func1
    func2()
  File "<ipython-input-42-2267707e164f>", line 7, in func2
    func3()
  File "<ipython-input-42-2267707e164f>", line 3, in func3
    print (my_list[3])
IndexError: list index out of range

Say we are not interested in some of the above information. Say we just want to print out the Traceback and skip the error message and Exception type (the last line above), then we can modify the code like shown below.

def func3():
  my_list = [1,2]
  print (my_list[3])

def func2():
  func3()

def func1():
  func2()

try:
  func1()
except Exception as e:
    traceback_lines = traceback.format_exc().splitlines()
    for line in traceback_lines:
      if line != traceback_lines[-1]:
        print(line)

Here we have used the format_exc() method available in the traceback class to get the traceback information as a string and used splitlines() method to transform the string into a list of lines and stored that in a list object named traceback_lines

Then with the help of a simple for loop we have skipped printing the last line with index of -1 to get an output like below

Traceback (most recent call last):
  File "<ipython-input-43-aff649563444>", line 3, in <module>
    func1()
  File "<ipython-input-42-2267707e164f>", line 11, in func1
    func2()
  File "<ipython-input-42-2267707e164f>", line 7, in func2
    func3()
  File "<ipython-input-42-2267707e164f>", line 3, in func3
    print (my_list[3])

Another interesting variant of formatting the information in the traceback object is to control the depth of stack that is actually printed out.

If your program uses lots of external library code, odds are the stack will get very deep, and printing out each and every level of function call might not be very useful. If you ever find yourself in such a situation you can set the limit argument in the print_exc() method like shown below.

traceback.print_exc(limit=2, file=sys.stdout)

This will limit the number of levels to 2. Let us use this line of code in our Example and see how that behaves

def func3():
  my_list = [1,2]
  print (my_list[3])

def func2():
  func3()

def func1():
  func2()

try:
  func1()
except Exception as e:
  traceback.print_exc(limit=2)

This will print

Traceback (most recent call last):
  File "<ipython-input-44-496132ff4faa>", line 12, in <module>
    func1()
  File "<ipython-input-44-496132ff4faa>", line 9, in func1
    func2()
IndexError: list index out of range

As you can see, we have printed only 2 levels of the stack and skipped the 3rd one, just as we wanted!

You can do more things with traceback like formatting the output to suit your needs. If you are interested to learn even more things to do, refer to the official documentation on traceback here

Now that we have seen how to exercise control over what gets printed and how to format them, next let us have a look at some best practices on when to use which piece of information

Best Practices while Printing Exception messages

When to Use Which Piece

  • Use Piece#1 only on very short programs and only during the development/testing phase to get some clues on the Exceptions without letting the interpreter crash your program. Once finding out, implement specific handlers to do something about these exceptions. If you are not sure how to handle the exceptions have a look at my other article below where I have explained 3 ways to handle Exceptions
    Exceptions in Python: Everything You Need To Know!
  • Use Piece#2 to print out some friendly information either for yourself or for your user to inform them what exactly is happening.
  • Use all 3 pieces on your finished product, so that if an exception ever occurs while your program is running on your client’s computer, you can log the errors and have use that information to fix your bugs.

Where to print

One point worth noting here is that the default file that print() uses is the stdout file stream and not the stderr stream. To use stderr instead, you can modify the code like this

import sys
try:
  #some naughty statements that irritate us with exceptions
except Exception as e:
  print(e, file=sys.stderr)

The above code is considered better practice, as errors are meant to go to stderr and not stdout.

You can always print these into a separate log file too if that is what you need. This way, you can organize the logs collected in a better manner by separating the informational printouts from the error printouts.

How to print into log files

If you are going to use a log file I suggest using python’s logging module instead of print() statements, as described here

If you are interested in learning how to manually raise exceptions, and what situations you might need to do that you can read this article below

Python: Manually throw/raise an Exception using the “raise” statement

If you are interested in catching and handling multiple exception in a single except clause, you can this article below

Python: 3 Ways to Catch Multiple Exceptions in a single “except” clause

And with that, I will conclude this article!
I hope you enjoyed reading this article and got some value out of it!
Feel free to share it with your friends and colleagues!

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

  • факт, что произошла ошибка
  • особенности произошедшей ошибки (ошибка, скрывающая антипаттерн)

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

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

Итак, как поймать общее исключение? Есть несколько способов. Если вы просто хотите объект исключения, сделайте следующее:

try:
    someFunction()
except Exception as ex:
    template = "An exception of type {0} occurred. Arguments:n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print message

Удостоверьтесь, что message доведено до сведения пользователя очень трудно! Печатать его, как показано выше, может быть недостаточно, если сообщение захоронено множеством других сообщений. Неспособность привлечь внимание пользователей равносильна проглатыванию всех исключений, и если у вас будет какое-то впечатление, что вам следует уйти после прочтения ответов на этой странице, это не очень хорошо. Завершение блока except с помощью оператора raise устраняет проблему путем прозрачного повторения исключения, которое было обнаружено.

Разница между приведенным выше и использованием только except: без каких-либо аргументов двояка:

  • Голый except: не дает вам объект исключения для проверки
  • Исключения SystemExit, KeyboardInterrupt и GeneratorExit не пойманы указанным выше кодом, что обычно является тем, что вы хотите. См. Иерархию исключений .

Если вы также хотите получить ту же стек, что и вы, если не поймаете исключение, вы можете получить это так (все еще внутри предложения except):

import traceback
print traceback.format_exc()

Если вы используете модуль logging, вы можете распечатать исключение в журнале (вместе с сообщением) следующим образом:

import logging
log = logging.getLogger()
log.exception("Message for you, sir!")

Если вы хотите углубиться и изучить стек, посмотреть на переменные и т.д., используйте функцию post_mortem pdb модуль внутри блока except:

import pdb
pdb.post_mortem()

Я нашел этот последний метод бесценным при поиске ошибок.

Цитата
Сообщение от alex925
Посмотреть сообщение

Веди логи и все, можешь сохранять полный traceback в лог.

Я с такой техникой не знаком. Зачем логи в разработке на Питоне?
В разработке мы оперируем срочной информацией. Вот оно упало — посмотрели, организовали обработчик исключений.

А логи — это на случай, если когда-то потом нам вдруг понадобится что-то. Так вот, при разработке-то оно нам может понадобиться только сейчас. И более никогда — потому что мы проехали и уже не хотим вспоминать, что мы кодили даже час назад.

В общем, что-то как-то — я уже утратил нить беседы. Все что ниже — это не троллинг, а попытка понять. Причина: alex925, я очень ценю Ваши сообщения. Если бы кто другой написал, я бы мимо ушей пропустил вообще. Но т.к. это написали Вы, я пытаюсь разобраться. Но мои попытки напоминают натягивание совы на глобус. Но давайте все-таки попробуем разобраться, как я Вас понял.

Вот мне в бытность студентом репетитор по Java говорил — чтобы быть продуктивным, кодишь до обеда, компилируешься, кодишь до вечера, компилируешься. Если будешь постоянно компилироваться, то времени на программирование не останется. Но у него-то был компилируемый язык. Т.е. — да, он кодил до обеда, и только потом ловил свои ошибки.

А еще давным давно мужики кодили на бумажке. Потом отдавали оператору. Оператор вбивал на перфокарты. Потом программист ждал освобождения машинного времени. Его перфокарты прогоняли. Он приходил. А там написано: «Ошибка компиляции». И он уходил думать. И думал опять на бумажке, опять наборщик и т.п.

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

Давайте все-таки определимся, почему Вы не хотите дать упасть в ошибку? Из этиж же самых соображений, что продуктивность программиста снизится из-за постоянных запусков?

Но как она может снизиться. Это же не компиляция. А на узнавание исключения в документации Вы все равно время потратите.

Польза лога может быть только в том случае, если вы кодите несколько часов без единого запуска. Потом запустился — без единой ошибки все прошло, все тесты отработали. Запустился — прощелкал на сайте кнопочики вручную — весь функционал работает без единой ошибки. Потому что если где необработанное исключение — уже не до лога будет.

И только потом заглянул в лог и узнал, какие исключения возникали. Но анализ лога не будет простым. В отличие от исключения, которое застрелило программу. И какая должна быть квалификация у программиста для такого.

В общем, был бы признателен за более подробный комментарий: почему вы против того, чтобы давать упасть, а только потом обрабатывать исключение.

  • Как получить 401 ошибку
  • Как полностью проверить ноутбук на ошибки
  • Как полностью проверить компьютер на ошибки windows 10
  • Как показывает опыт к наиболее общим ошибкам пауэрлифтеров относятся то что спортсмены
  • Как показывает опыт к наиболее общим ошибкам пауэрлифтеров относят то что спортсмены