如何引发包含 Unicode 字符串的异常? [英] How can I raise an Exception that includes a Unicode string?

查看:65
本文介绍了如何引发包含 Unicode 字符串的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Unicode 字符串编写 Python 2 代码,导入 unicode_literals,但在引发异常时遇到问题.

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')

执行此操作时,'Tést' 字符串将从终端中剥离.

When doing this, the 'Tést' string is stripped off the terminal.

我可以解决这个问题

raise Exception('Tést'.encode('utf-8'))

我宁愿找到一个全局解决方案,也不愿在所有raise Exception 语句中都这样做.

I'd rather find a global solution than having to do this in all raise Exception statements.

(由于我在异常消息中使用了PyQt的tr()函数,必须处理特殊字符,编码时不知道encode('utf-8') 是必要的.)

(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.

我必须这样做:

try:
    raise TypeError('Tést'.encode('utf-8'))
except Exception as e:
    raise Exception('Exception: {}'.format(str(e).decode('utf-8')).encode('utf-8'))

但我真的希望它可以不那么麻烦(这个例子甚至不包括 self.tr() 调用).

but I really wish it could be less cumbersome (and this example doesn't even include the self.tr() calls).

有没有更简单的方法?

(作为一个附带问题,Python3 的事情是否更简单?异常可以使用 unicode 字符串吗?)

(And as a side question, are things simpler with Python3 ? Can Exception use unicode strings ?)

推荐答案

感谢问题下方的评论,我想出了这个.

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

这个想法是使用自定义的 Exception 子类.

The idea is to use a custom Exception subclass.

# -*- coding: utf-8 -*-

from __future__ import unicode_literals

class MyException(Exception):

    def __init__(self, message):

        if isinstance(message, unicode):
            super(MyException, self).__init__(message.encode('utf-8'))
            self.message = message

        elif isinstance(message, str):
            super(MyException, self).__init__(message)
            self.message = message.decode('utf-8')

        # This shouldn't happen...
        else:
            raise TypeError

    def __unicode__(self):

        return self.message

class MySubException(MyException):
    pass

try:
    raise MyException('Tést')
except MyException as e:
    print(e.message)
    raise MySubException('SubException: {}'.format(e))

这篇关于如何引发包含 Unicode 字符串的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆