How can I actually print out the ValueError's message after I catch it?
If I type except ValueError, err:
into my code instead of except ValueError as err:
, I get the error SyntaxError: invalid syntax
.
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.
If you want the error class, error message, and stack trace, use sys. exc_info() . The function sys. exc_info() gives you details about the most recent exception.
Here is a simple example to handle ValueError exception using try-except block. import math x = int(input('Please enter a positive number:\n')) try: print(f'Square Root of {x} is {math. sqrt(x)}') except ValueError as ve: print(f'You entered {x}, which is not a positive number.
Python3. Method 2: By using print_exception() method. This method prints exception information and stack trace entries from traceback object tb to file.
try: ... except ValueError as e: print(e)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With