I'm writing Python 2 code with Unicode strings, importing unicode_literals and I'm having issues with raising exceptions.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
raise Exception('Tést')
When doing this, the 'Tést' string is stripped off the terminal.
I can workaround this with
raise Exception('Tést'.encode('utf-8'))
I'd rather find a global solution than having to do this in all raise Exception
statements.
(Since I'm using PyQt's tr()
function in Exception messages, special characters must be handled, I can't know at coding time whether encode('utf-8')
is necessary.)
Worse. Sometimes, I want to catch an Exception, get its message, and raise a new Exception, concatenating a base string with the first Exception string.
I have to do it this way:
try:
raise TypeError('Tést'.encode('utf-8'))
except Exception as e:
raise Exception('Exception: {}'.format(str(e).decode('utf-8')).encode('utf-8'))
but I really wish it could be less cumbersome (and this example doesn't even include the self.tr()
calls).
Is there any simpler way ?
(And as a side question, are things simpler with Python3 ? Can Exception use unicode strings ?)