How to print exception python
How to print exception python
8. Errors and ExceptionsВ¶
Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.
8.1. Syntax ErrorsВ¶
Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:
8.2. ExceptionsВ¶
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:
The rest of the line provides detail based on the type of exception and what caused it.
The preceding part of the error message shows the context where the exception occurred, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.
Built-in Exceptions lists the built-in exceptions and their meanings.
8.3. Handling ExceptionsВ¶
The try statement works as follows.
First, the try clause (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:
A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order:
Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.
The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.
When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the argument depend on the exception type.
If an exception has arguments, they are printed as the last part (вЂdetail’) of the message for unhandled exceptions.
Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For example:
8.4. Raising ExceptionsВ¶
The raise statement allows the programmer to force a specified exception to occur. For example:
The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception ). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:
If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:
8.5. Exception ChainingВ¶
The raise statement allows an optional from which enables chaining exceptions. For example:
This can be useful when you are transforming exceptions. For example:
Exception chaining happens automatically when an exception is raised inside an except or finally section. This can be disabled by using from None idiom:
8.6. User-defined ExceptionsВ¶
Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derived from the Exception class, either directly or indirectly.
Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception.
Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions.
8.7. Defining Clean-up ActionsВ¶
The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:
If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception. The following points discuss more complex cases when an exception occurs:
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.
An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.
If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement.
A more complicated example:
As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.
In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.
8.8. Predefined Clean-up ActionsВ¶
Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen.
The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.
After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.
How to print an exception in Python 3?
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I’m guessing that you need to assign the Exception to a variable. As shown in the Python 3 tutorial:
To give a brief explanation, as is a pseudo-assignment keyword used in certain compound statements to assign or alias the preceding statement to a variable.
In this case, as assigns the caught exception to a variable allowing for information about the exception to stored and used later, instead of needing to be dealt with immediately.
Here, with statements are used to wrap the execution of a block with methods defined by context managers. This functions like an extended try. except. finally statement in a neat generator package, and the as statement assigns the generator-produced result from the context manager to a variable for extended use.
As of Python 3.10, match statements also use as :
match statements take an expression (in this case, randint(0, 2) ) and compare its value to each case branch one at a time until one of them succeeds, at which point it executes that branch’s block. In a case branch, as can be used to assign the value of the branch to a variable if that branch succeeds. If it doesn’t succeed, it is not bound.
(The match statement is covered by the tutorial and discussed in detail in the Python 3 Language Reference: match Statements.)
Finally, as can be used when importing modules, to alias a module to a different (usually shorter) name:
How to get exception message in Python properly
What is the best way to get exceptions’ messages from components of standard library in Python?
I noticed that in some cases you can get it via message field like this:
but in some cases (for example, in case of socket errors) you have to do something like this:
I wondered is there any standard way to cover most of these situations?
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you look at the documentation for the built-in errors, you’ll see that most Exception classes assign their first argument as a message attribute. Not all of them do though.
More generally, subclasses of Exception can do whatever they want. They may or may not have a message attribute. Future built-in Exception s may not have a message attribute. Any Exception subclass imported from third-party libraries or user code may not have a message attribute.
If you must print something, I think that printing the caught Exception itself is most likely to do what you want, whether it has a message attribute or not.
You could also check for the message attribute if you wanted, like this, but I wouldn’t really suggest it as it just seems messy:
How to Catch and Print Exception Messages in Python
An exception will immediately terminate your program. To avoid this, you can catch the exception with a try/except block around the code where you expect that a certain exception may occur. Here’s how you catch and print a given exception:
Table of Contents
Example 1: Catch and Print IndexError
If you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an IndexError telling you that the list index is out of range.
Your genius code attempts to access the fourth element in your list with index 3—that doesn’t exist!
Fortunately, you wrapped the code in a try/catch block and printed the exception. The program is not terminated. Thus, it executes the final print() statement after the exception has been caught and handled. This is the output of the previous code snippet.
Example 2: Catch and Print ValueError
The ValueError arises if you try to use wrong values in some functions. Here’s an example where the ValueError is raised because you tried to calculate the square root of a negative number:
The output shows that not only the error message but also the string ‘Am I executed?’ is printed.
Example 3: Catch and Print TypeError
Python throws the TypeError object is not subscriptable if you use indexing with the square bracket notation on an object that is not indexable. This is the case if the object doesn’t define the __getitem__() method. Here’s how you can catch the error and print it to your shell:
The output shows that not only the error message but also the string ‘Am I executed?’ is printed.
I hope you’re now able to catch and print your error messages.
Summary
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
Programmer Humor
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Related Tutorials
Why Finxter?
Learning Resources
How do I print an exception in Python?
How do I print the error/exception in the except: block?
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
For Python 2.6 and later and Python 3.x:
For Python 2.5 and earlier, use:
The traceback module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:
In Python 2.6 or greater it’s a bit cleaner:
In older versions it’s still quite readable:
Python 3: logging
Instead of using the basic print() function, the more flexible logging module can be used to log the exception. The logging module offers a lot extra functionality, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened. (For more information check out the official documentation.)
Logging an exception can be done with the module-level function logging.exception() like so:
Output:
Notes:
the function logging.exception() should only be called from an exception handler
the logging module should not be used inside a logging handler to avoid a RecursionError (thanks @PrakharPandey)
Alternative log-levels
It’s also possible to log the exception with another log-level by using the keyword argument exc_info=True like so:
In case you want to pass error strings, here is an example from Errors and Exceptions (Python 2.6)
(I was going to leave this as a comment on @jldupont’s answer, but I don’t have enough reputation.)
I’ve seen answers like @jldupont’s answer in other places as well. FWIW, I think it’s important to note that this:
will print the error output to sys.stdout by default. A more appropriate approach to error handling in general would be:
I haven’t used the traceback module as in Cat Plus Plus’s answer, and maybe that’s the best way, but I thought I’d throw this out there.
Источники информации:
- http://stackoverflow.com/questions/41596810/how-to-print-an-exception-in-python-3
- http://stackoverflow.com/questions/33239308/how-to-get-exception-message-in-python-properly
- http://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/
- http://stackoverflow.com/questions/1483429/how-to-print-an-exception-in-python?lq=1