Monday, 15 August 2011

python - How can I raise an Exception that includes a Unicode string? -


I am writing Python 2 code with Unicode strings, importing Unicode_titles and I have issues with exceptions .

<-> <-> - <-> Coding: Import Unicode _ Literal Exception ('Test') from UTF-8 - * - __future__

Do this Time, the 'test' string terminal has been stripped.

I can work with it to increase exceptions ('test' .code ('utf-8')) < P> I want to find a global solution instead of doing this in all the exceptions statements.

(Since I need to handle exception codes, special characters in PyQt's TR () function, I do not know at the time of coding that encode ('utf- 8 ') is required.)

worse than that. Occasionally, I want to catch exceptions, get my message, and increase a new exception, first add the original string with the exception string.

I have to do this like this:

  Effort: raise typeError (except 'Tést'.encode (' utf-8 ')) Exception: E: Exception 'Exception: {}' format (str (e) .decode ('utf-8')) encode ('utf-8'))  

But I really Wish it may be less cumbersome (and in this example self.tr () calls).

Is there any easy way?

(And as a side question, is things easier with Python 3? Can Exceptions Unicode String Use?)

Thanks for the comments below the question, I came up with this.

The idea is to use custom exception subclass. Importing from Unicode_Lights class MyException (exception): def __init __ (auto, message): if isinstance (message, unicode): Super:

  # - * - coding: UTF-8 - * - __future__ (MyExation, Self) .__ init __ (message.encode ('utf-8')) self.message = message elif isinstance (message, str): super (miexation, self) .__ init __ (message) self.message = Message .decode ('utf-8') # It should not be ... else: TypeError def __unicode __ (self): return self. Message class MySubException: Try the following: Increase MyException ('Teet') except MyException E: Increase MySubException as Print (e-Message) ('subexception: {}'. Format (e))  

No comments:

Post a Comment