Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Catch and Print Exception Messages in Python

#1
How to Catch and Print Exception Messages in Python

Python comes with an extensive support of exceptions and exception handling. An exception event interrupts and, if uncaught, immediately terminates a running program. The most popular examples are the IndexError, ValueError, and TypeError.

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:

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e. You can now print the error message with "print(e)" or use it for further processing.

try: # ... YOUR CODE HERE ... #
except Exception as e: # ... PRINT THE ERROR MESSAGE ... # print(e)

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.

try: lst = ['Alice', 'Bob', 'Carl'] print(lst[3])
except Exception as e: print(e) print('Am I executed?')

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.

list index out of range
Am I executed?

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:

import math try: a = math.sqrt(-2)
except Exception as e: print(e) print('Am I executed?')

The output shows that not only the error message but also the string 'Am I executed?' is printed.

math domain error
Am I executed?

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:

try: variable = None print(variable[0])
except Exception as e: print(e) print('Am I executed?')

The output shows that not only the error message but also the string 'Am I executed?' is printed.

'NoneType' object is not subscriptable
Am I executed?

I hope you’re now able to catch and print your error messages.

Summary


To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e. You can now print the error message with "print(e)" or use it for further processing.

Where to Go From Here?


Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

The post How to Catch and Print Exception Messages in Python first appeared on Finxter.



https://www.sickgaming.net/blog/2020/11/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Print a NumPy Array Without Scientific Notation in Python xSicKxBot 0 1,220 10-20-2022, 11:44 AM
Last Post: xSicKxBot
  [Tut] Python Print Dictionary Values Without “dict_values” xSicKxBot 0 1,362 10-12-2022, 02:48 AM
Last Post: xSicKxBot
  [Tut] Python Print Dictionary Without One Key or Multiple Keys xSicKxBot 0 1,255 10-10-2022, 08:56 PM
Last Post: xSicKxBot
  [Tut] How to Print a List Without Commas in Python xSicKxBot 0 1,228 10-08-2022, 08:06 AM
Last Post: xSicKxBot
  [Tut] Python Print List Without Truncating xSicKxBot 0 1,361 10-07-2022, 12:21 PM
Last Post: xSicKxBot
  [Tut] How to Print a List Without Newline in Python? xSicKxBot 0 1,077 09-04-2022, 12:21 PM
Last Post: xSicKxBot
  [Tut] How to Print a List Without Brackets and Commas in Python? xSicKxBot 0 1,173 08-27-2022, 03:30 AM
Last Post: xSicKxBot
  [Tut] How to Print a String and an Integer xSicKxBot 0 1,282 08-25-2022, 10:37 AM
Last Post: xSicKxBot
  [Tut] [FIXED] Carriage return Not Working with Print in VS Code xSicKxBot 0 1,179 06-10-2022, 10:21 PM
Last Post: xSicKxBot
  [Tut] How to Overwrite the Previous Print to Stdout in Python? xSicKxBot 0 1,263 05-29-2022, 01:47 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016