raising an Exception in an Except without calling the original Exception


This question already has an answer here:


Quoting the docs:

When raising (or re-raising) an exception in an except or finally clause __context__ is automatically set to the last exception caught; if the new exception is not handled the traceback that is eventually displayed will include the originating exception(s) and the final exception.

This is exactly your case:

        raise ValueError
    except ValueError:
        raise TypeError
except Exception as e:
    print('Original:', type(e.__context__)) # Original: <class 'ValueError'>
    print('Explicitly raised:', type(e))    # Explicitly raised: <class 'TypeError'>

There's only one active exception; I might have written except TypeError instead of except Exception and the output would still be the same.

If you want to prevent Python from printing the original exception, use raise ... from None:

    raise ValueError
except ValueError:
    raise TypeError from None

Need Your Help

How to pass command line parameters to a batch file?

windows batch-file command-line cmd

I need to pass id and password to a cmd (or bat) file at the time of running rather than hardcoding them into the file.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.