GVKun编程网logo

在Python中,如何在维护原始调用堆栈的同时检查并重新引发异常?

12

在本文中,我们将详细介绍在Python中,如何在维护原始调用堆栈的同时检查并重新引发异常?的各个方面,同时,我们也将为您带来关于c#–如何自动重新引发异常、Python2.x和3.x中的有效语法是否引

在本文中,我们将详细介绍在Python中,如何在维护原始调用堆栈的同时检查并重新引发异常?的各个方面,同时,我们也将为您带来关于c# – 如何自动重新引发异常、Python 2.x和3.x中的有效语法是否引发异常?、python – 如何在分配给未映射到SQLAlchemy列的属性时引发异常?、Python中使用堆栈的嵌套括号的有用知识。

本文目录一览:

在Python中,如何在维护原始调用堆栈的同时检查并重新引发异常?

在Python中,如何在维护原始调用堆栈的同时检查并重新引发异常?

我遇到一种情况,我正在捕获特定的异常类型,检查异常的消息以检查它是否确实是我要捕获的异常,然后重新引发该异常(如果不是):

try:
    # do something exception-prone
except FooException as e:
    if e.message == 'Something I want to handle':
        # handle the exception
    else:
        raise e

这很好,但有一个问题。在我重新引发异常的情况下,该异常现在发生在我重新引发该异常的行(即raise e),而不是在异常最初发生的位置。对于您想知道原始异常发生在哪里的调试来说,这不是理想的选择。

因此,我的问题是:在保持原始异常位置的同时,捕获异常之后,是否有任何方法可以重新引发或以其他方式“传递”异常?

注意:如果您想知道实际情况是什么:我正在使用动态导入一些模块__import__。我正在ImportError设法优雅地处理所有这些模块都不存在的情况。但是,如果这些模块中的任何一个本身包含import语句引发ImportError,我都希望引发那些“真实的”(从我的应用程序的角度来看)异常-
在调试工具的原始位置关注。

c# – 如何自动重新引发异常

c# – 如何自动重新引发异常

如果在try catch块中包装对HttpResponse.End的调用,则会自动重新引发ThreadAbortException.我假设即使你在try catch块中包装try catch块也是如此.

我怎样才能完成同样的事情?我没有这方面的实际应用程序.

namespace Program
{
    class ReJoice
    {
        public void End() //This does not automatically re-raise the exception if caught.  
        {
            throw new Exception();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ReJoice x = new ReJoice();
                x.End();
            }
            catch (Exception e) {}
        }
    }
}

解决方法

您无法更改普通例外以获得此行为. ThreadAbortException对此有特殊支持,您无法在C#中实现自己.

ThreadAbortException is a special exception that can be caught,but it will automatically be raised again at the end of the catch block.

Python 2.x和3.x中的有效语法是否引发异常?

Python 2.x和3.x中的有效语法是否引发异常?

如何将这段代码移植到Python 3,使其可以在Python 2和Python3中运行?

raise BarException,BarException(e),sys.exc_info()[2]

(从http://blog.ionelmc.ro/2014/08/03/the-most-underrated-feature-in-
python-3/复制)

奖励问题
做类似的事情有意义吗

IS_PYTHON2 = sys.version_info < (3,0)

if IS_PYTHON2:
    raise BarException,sys.exc_info()[2]
    # replace with the code that would run in Python 2 and Python 3 respectively
else:
    raise BarException("Bar is closed on Christmas")

python – 如何在分配给未映射到SQLAlchemy列的属性时引发异常?

python – 如何在分配给未映射到SQLAlchemy列的属性时引发异常?

使用sqlAlchemy,我发现有时候我错误地键入了一个映射到列的属性的名称,这导致很难捕获错误:

class Thing(Base):
    foo = Column(String)


thing = Thing()
thing.bar = "Hello" # a typo,I actually meant thing.foo
assert thing.bar == "Hello" # works here,as thing.bar is a transient attribute created by the assignment above
session.add(thing)
session.commit() # thing.bar is not saved in the database,obvIoUsly
...
# much later
thing = session.query(Thing)...one()
assert thing.foo == "Hello" # fails
assert thing.bar == "Hello" # fails,there''s no even such attribute

有没有办法配置映射类,因此分配给未映射到sqlAlchemy列的任何内容都会引发异常?

解决方法

好的,解决方案似乎是覆盖基类的__setattr__方法,这允许我们在设置之前检查属性是否已经存在.

class BaseBase(object):
    """
    This class is a superclass of SA-generated Base class,which in turn is the superclass of all db-aware classes
    so we can define common functions here
    """

    def __setattr__(self,name,value):
        """
        Raise an exception if attempting to assign to an atribute which does not exist in the model.
        We''re not checking if the attribute is an sqlAlchemy-mapped column because we also want it to work with properties etc.
        See https://stackoverflow.com/questions/12032260/ for more details.
        """ 
        if name != "_sa_instance_state" and not hasattr(self,name):
            raise AttributeError("Attribute %s is not a mapped column of object %s" % (name,self))
        super(BaseBase,self).__setattr__(name,value)

Base = declarative_base(cls=BaseBase)

sqlAlchemy的“严格模式”排序……

Python中使用堆栈的嵌套括号

Python中使用堆栈的嵌套括号

如何解决Python中使用堆栈的嵌套括号?

如果不嵌套则返回 0 嵌套返回 1

我不知道下面的代码有什么问题。即使对于不平衡的括号,它也会返回 1。

#from codility
def solution (S):
    B =[]
    
    if len(S) == 0:
        return 1
    for i in range (0,len(S)):
        if S[i] == "(" or S[i] == "[" or S[i] == "{":
            B.append(S[i])
        else: 
            return 0
        if (S[i] == ")" and B[-1]!= "(") :
            return 0
        if (S[i] == "}" and B[-1]!= "{") :
            return 0
        if (S[i] == "]" and B[-1]!= "[") :
            return 0
        else:
            B.pop()

        if len(B)==0:   
            return 1

解决方法

定义解决方案(S): B =[]

if len(S) == 0:
    return 1
for i in range (0,len(S)):
    if S[i] == "(" or S[i] == "[" or S[i] == "{":
        B.append(S[i])
    else: 
        return 0
    if (S[i] == ")" and B[-1]!= "(") :
        return 0
    if (S[i] == "}" and B[-1]!= "{") :
        return 0
    if (S[i] == "]" and B[-1]!= "[") :
        return 0
    else:
        B.pop()
if len(B)==0:   
        return 1

这导致了问题,因为 B 的初始长度为 0,因此循环从 i=0 len(B) == 0 开始并返回 1。

尝试将其置于循环之外。

今天关于在Python中,如何在维护原始调用堆栈的同时检查并重新引发异常?的讲解已经结束,谢谢您的阅读,如果想了解更多关于c# – 如何自动重新引发异常、Python 2.x和3.x中的有效语法是否引发异常?、python – 如何在分配给未映射到SQLAlchemy列的属性时引发异常?、Python中使用堆栈的嵌套括号的相关知识,请在本站搜索。

本文标签: