Raise exception without quitting the program

4k views Asked by At

I'm on Windows and using python 3.7.7. I am trying to make a golfing language. In that e. if you raise an Exception (to be clear NameError) like this:

raise NameError("Your input was not recognized as a function, variable or  datatype")

Then the program automatically quits. When I tried this:

 print(NameError("Your input was not recognized as a function, variable or  datatype"))

Then it prints the error but not fully and not in red like this: Your input was not recognized as a function, variable or datatype

Is there a way that the program should not quit and print a real error?

3

There are 3 answers

3
AudioBubble On

I'm surprised no one has mentioned the Python termcolor module. Usage is pretty simple:

from termcolor import colored

Python 2:

print colored('hello', 'red'), colored('world', 'green')

Or in Python 3:

print(colored('hello', 'red'), colored('world', 'green'))

Along with the use of "try-except" statement, since after all, you can raise exceptions without quitting the program, by adding something in the except clause.

0
jvieira88 On

In the absence of more details, you can try something like this:

try:
    raise(NameError("Your input was not recognized as a function, variable or  datatype"))
except Exception as e:
    print(repr(e))

However, this is not exactly how exceptions should be used.

0
math scat On

After long research I found an answer: This doesn't raise an error but prints colored error in both terminal and shell

  1. Install CLINT with pip
pip install clint
  1. In Python
import sys
try:
    sys.stdout.shell.write("Your input was not recognized as a variable, function or datatype\n", "COMMENT")
except AttributeError:
    puts(colored.red("Your input was not recognized as a variable, function or datatype"))