Python How to Catch and Print Assertion Errors in Python

Click For Summary
The discussion centers on managing error output in Python, specifically how to suppress detailed traceback information when an assertion fails. It emphasizes that traceback details, including the file and line number, are crucial for debugging and should not be hidden. For user-facing messages, using try...except blocks is recommended instead of allowing the program to crash. The conversation also highlights the use of assertRaises in unit testing, which is a method to test that specific exceptions are raised during code execution. Participants suggest that if the user is unfamiliar with assertRaises, they should explore unit testing frameworks and learn how to handle assertions properly, including catching AssertionErrors to retrieve and display relevant messages.
Sunwoo Bae
Messages
60
Reaction score
4
1581924271419.png

I would like to make output only read:

Traceback (most recent call last):
AssertionError

... without giving the File "<input>", line 1, in <module>
 
Technology news on Phys.org
1581925677016.png
 
Why? The line number is there to help you debug your code. If this is to show a message to an end user then you should be using try...except, not just letting the program fail.
 
Oh its for unit testing? You should use assertRaises in your test instead of testing the crash dump output.
 
pbuk said:
Oh its for unit testing? You should use assertRaises in your test instead of testing the crash dump output.
can you tell me what assertRaises exactly do and how to use it? I have never heard about it :(
 
Hmmm, looking again I am not sure you are using a unit test framework. Is this an online tutorial? If so, stick with my first answer: catch the assertion and print its message. You can look up how to catch the failing assertion with try...except and how to get the message string from an AssertionError in a Python reference if you haven't covered them already (have you skipped some of the tutorial?).
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 29 ·
Replies
29
Views
3K
Replies
1
Views
2K
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 9 ·
Replies
9
Views
9K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
4K