4/20/2020 Sm Has Thown A Generic Pyton Exception
After seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. In this article, you saw the following options: raise allows you to throw an exception at any time. Assert enables you to verify if a certain condition is met and throw an exception if it isn’t. Exception Handling in Python. Exception handling is a concept used in Python to handle the exceptions and errors that occur during the execution of any program. Exceptions are unexpected errors that can occur during code execution. We have covered about exceptions and errors in python in the last tutorial.
![]()
Exception HandlingThe functions described in this chapter will let you handle and raise Pythonexceptions. It is important to understand some of the basics of Pythonexception handling. It works somewhat like the Unix errno variable:there is a global indicator (per thread) of the last error that occurred. Mostfunctions don’t clear this on success, but will set it to indicate the cause ofthe error on failure. Most functions also return an error indicator, usuallyNULL if they are supposed to return a pointer, or -1 if they return aninteger (exception: the PyArg.
functions return 1 for success and0 for failure).When a function must fail because some function it called failed, it generallydoesn’t set the error indicator; the function it called already set it. It isresponsible for either handling the error and clearing the exception orreturning after cleaning up any resources it holds (such as object references ormemory allocations); it should not continue normally if it is not prepared tohandle the error. If returning due to an error, it is important to indicate tothe caller that an error has been set. If the error is not handled or carefullypropagated, additional calls into the Python/C API may not behave as intendedand may fail in mysterious ways.The error indicator consists of three Python objects corresponding to thePython variables sys.exctype, sys.excvalue and sys.exctraceback.API functions exist to interact with the error indicator in various ways. Thereis a separate error indicator for each thread.void PyErrPrintEx (int setsyslastvars )Print a standard traceback to sys.stderr and clear the error indicator.Unless the error is a SystemExit.
In that case the no tracebackis printed and Python process will exit with the error code specified bythe SystemExit instance.Call this function only when the error indicator is set. Otherwise itwill cause a fatal error!If setsyslastvars is nonzero, the variables,and will be set to thetype, value and traceback of the printed exception, respectively.void PyErrPrint ( )Alias for PyErrPrintEx(1). PyErrOccurred ( ) Return value: Borrowed reference.Test whether the error indicator is set. If set, return the exception type(the first argument to the last call to one of the PyErrSet.functions or to ). If not set, return NULL. You do notown a reference to the return value, so you do not need toit. NoteDo not compare the return value to a specific exception; useinstead, shown below.
(The comparison couldeasily fail since the exception may be an instance instead of a class, in thecase of a class exception, or it may be a subclass of the expected exception.)int PyErrExceptionMatches (.exc )Equivalent to PyErrGivenExceptionMatches(PyErrOccurred, exc). Thisshould only be called when an exception is actually set; a memory accessviolation will occur if no exception has been raised.int PyErrGivenExceptionMatches (.given,.exc )Return true if the given exception matches the exception in exc.
Ifexc is a class object, this also returns true when given is an instanceof a subclass. If exc is a tuple, all exceptions in the tuple (andrecursively in subtuples) are searched for a match.void PyErrNormalizeException (.exc,.val,.tb )Under certain circumstances, the values returned by belowcan be “unnormalized”, meaning that.exc is a class object but.val isnot an instance of the same class. This function can be used to instantiatethe class in that case. If the values are already normalized, nothing happens.The delayed normalization is implemented to improve performance.void PyErrClear ( )Clear the error indicator. If the error indicator is not set, there is noeffect.void PyErrFetch (.ptype,.pvalue,.ptraceback )Retrieve the error indicator into three variables whose addresses are passed.If the error indicator is not set, set all three variables to NULL. If it isset, it will be cleared and you own a reference to each object retrieved. Thevalue and traceback object may be NULL even when the type object is not.
NoteThis function is normally only used by code that needs to handle exceptions orby code that needs to save and restore the error indicator temporarily.void PyErrRestore (.type,.value,.traceback )Set the error indicator from the three objects. If the error indicator isalready set, it is cleared first. If the objects are NULL, the errorindicator is cleared. Do not pass a NULL type and non- NULL value ortraceback. The exception type should be a class. Do not pass an invalidexception type or value.
(Violating these rules will cause subtle problemslater.) This call takes away a reference to each object: you must own areference to each object before the call and after the call you no longer ownthese references. (If you don’t understand this, don’t use this function. Iwarned you.). NoteThis function is normally only used by code that needs to save and restore theerror indicator temporarily; use to save the currentexception state.void PyErrSetString (.type, const char.message )This is the most common way to set the error indicator. The first argumentspecifies the exception type; it is normally one of the standard exceptions,e.g.
You need not increment its reference count.The second argument is an error message; it is converted to a string object.void PyErrSetObject (.type,.value )This function is similar to but lets you specify anarbitrary Python object for the “value” of the exception. PyErrFormat (.exception, const char.format. ) Return value: Always NULL.This function sets the error indicator and returns NULL. Exceptionshould be a Python exception class. The format and subsequentparameters help format the error message; they have the same meaning andvalues as in.void PyErrSetNone (.type )This is a shorthand for PyErrSetObject(type, PyNone).int PyErrBadArgument ( )This is a shorthand for PyErrSetString(PyExcTypeError, message), wheremessage indicates that a built-in operation was invoked with an illegalargument.
It is mostly for internal use. PyErrNoMemory ( ) Return value: Always NULL.This is a shorthand for PyErrSetNone(PyExcMemoryError); it returns NULLso an object allocation function can write return PyErrNoMemory; when itruns out of memory. PyErrSetFromErrno (.type ) Return value: Always NULL.This is a convenience function to raise an exception when a C library functionhas returned an error and set the C variable errno.
It constructs atuple object whose first item is the integer errno value and whosesecond item is the corresponding error message (gotten from strerror),and then calls PyErrSetObject(type, object). On Unix, when theerrno value is EINTR, indicating an interrupted system call,this calls, and if that set the error indicator,leaves it set to that. The function always returns NULL, so a wrapperfunction around a system call can write return PyErrSetFromErrno(type);when the system call returns an error. PyErrSetFromErrnoWithFilenameObject (.type,.filenameObject )Similar to, with the additional behavior that iffilenameObject is not NULL, it is passed to the constructor of type asa third parameter. In the case of exceptions such as and, this is used to define the filename attribute of theexception instance. PyErrSetFromErrnoWithFilename (.type, const char.filename ) Return value: Always NULL.Similar to, but the filenameis given as a C string. PyErrSetFromWindowsErr (int ierr ) Return value: Always NULL.This is a convenience function to raise.
If called withierr of 0, the error code returned by a call to GetLastErroris used instead. It calls the Win32 function FormatMessage to retrievethe Windows description of error code given by ierr or GetLastError,then it constructs a tuple object whose first item is the ierr value and whosesecond item is the corresponding error message (gotten fromFormatMessage), and then calls PyErrSetObject(PyExcWindowsError, object). This function always returns NULL. Availability: Windows.
![]()
PyErrSetExcFromWindowsErr (.type, int ierr ) Return value: Always NULL.Similar to, with an additional parameterspecifying the exception type to be raised. Availability: Windows.
New in version 2.3. PyErrSetFromWindowsErrWithFilenameObject (int ierr,.filenameObject )Similar to, with the additional behavior thatif filenameObject is not NULL, it is passed to the constructor ofas a third parameter. Availability: Windows. PyErrSetFromWindowsErrWithFilename (int ierr, const char.filename ) Return value: Always NULL.Similar to, but thefilename is given as a C string. Availability: Windows. PyErrSetExcFromWindowsErrWithFilenameObject (.type, int ierr,.filename )Similar to, with anadditional parameter specifying the exception type to be raised.Availability: Windows. New in version 2.3.void PyErrBadInternalCall ( )This is a shorthand for PyErrSetString(PyExcSystemError, message),where message indicates that an internal operation (e.g.
A Python/C APIfunction) was invoked with an illegal argument. It is mostly for internaluse.int PyErrWarnEx (.category, char.message, int stacklevel )Issue a warning message.
The category argument is a warning category (seebelow) or NULL; the message argument is a message string. Stacklevel is apositive number giving a number of stack frames; the warning will be issued fromthe currently executing line of code in that stack frame. A stacklevel of 1is the function calling, 2 is the function above that,and so forth.This function normally prints a warning message to sys.stderr; however, it isalso possible that the user has specified that warnings are to be turned intoerrors, and in that case this will raise an exception. It is also possible thatthe function raises an exception because of a problem with the warning machinery(the implementation imports the module to do the heavy lifting).The return value is 0 if no exception is raised, or -1 if an exceptionis raised. (It is not possible to determine whether a warning message isactually printed, nor what the reason is for the exception; this isintentional.) If an exception is raised, the caller should do its normalexception handling (for example, owned references and returnan error value).Warning categories must be subclasses of PyExcWarning;PyExcWarning is a subclass of PyExcException;the default warning category is PyExcRuntimeWarning.
The standardPython warning categories are available as global variables whose names areenumerated at.For information about warning control, see the documentation for themodule and the option in the command linedocumentation. There is no C API for warning control.int PyErrWarn (.category, char.message )Issue a warning message. The category argument is a warning category (seebelow) or NULL; the message argument is a message string.
The warning willappear to be issued from the function calling, equivalent tocalling with a stacklevel of 1.Deprecated; use instead.int PyErrWarnExplicit (.category, const char.message, const char.filename, int lineno, const char.module,.registry )Issue a warning message with explicit control over all warning attributes. Thisis a straightforward wrapper around the Python function, see there for more information. The moduleand registry arguments may be set to NULL to get the default effectdescribed there.int PyErrWarnPy3k (char.message, int stacklevel )Issue a with the given message and stacklevelif the PyPy3kWarningFlag flag is enabled. New in version 2.6.int PyErrCheckSignals ( )This function interacts with Python’s signal handling.
It checks whether asignal has been sent to the processes and if so, invokes the correspondingsignal handler. If the module is supported, this can invoke asignal handler written in Python. In all cases, the default effect forSIGINT is to raise the exception. If anexception is raised the error indicator is set and the function returns -1;otherwise the function returns 0.
The error indicator may or may not becleared if it was previously set.void PyErrSetInterrupt ( )This function simulates the effect of a SIGINT signal arriving — thenext time is called, willbe raised. It may be called without holding the interpreter lock.int PySignalSetWakeupFd (int fd )This utility function specifies a file descriptor to which a '0' byte willbe written whenever a signal is received. It returns the previous such filedescriptor.
The value -1 disables the feature; this is the initial state.This is equivalent to in Python, but without anyerror checking. Fd should be a valid file descriptor. The function shouldonly be called from the main thread. New in version 2.6. PyErrNewException (char.name,.base,.dict ) Return value: New reference.This utility function creates and returns a new exception class.
The nameargument must be the name of the new exception, a C string of the formmodule.classname. The base and dict arguments are normally NULL.This creates a class object derived from (accessible in C asPyExcException).The module attribute of the new class is set to the first part (upto the last dot) of the name argument, and the class name is set to the lastpart (after the last dot). The base argument can be used to specify alternatebase classes; it can either be only one class or a tuple of classes. The dictargument can be used to specify a dictionary of class variables and methods. PyErrNewExceptionWithDoc (char.name, char.doc,.base,.dict ) Return value: New reference.Same as, except that the new exception class caneasily be given a docstring: If doc is non- NULL, it will be used as thedocstring for the exception class. Recursion ControlThese two functions provide a way to perform safe recursive calls at the Clevel, both in the core and in extension modules.
They are needed if therecursive code does not necessarily invoke Python code (which tracks itsrecursion depth automatically).int PyEnterRecursiveCall (const char.where )Marks a point where a recursive C-level call is about to be performed.If USESTACKCHECK is defined, this function checks if the OSstack overflowed using. In this is the case, itsets a and returns a nonzero value.The function then checks if the recursion limit is reached. If this is thecase, a is set and a nonzero value is returned.Otherwise, zero is returned.where should be a string such as ' in instance check' to beconcatenated to the message caused by the recursion depthlimit.void PyLeaveRecursiveCall ( )Ends a. Must be called once for eachsuccessful invocation of. Standard ExceptionsAll standard Python exceptions are available as global variables whose names arePyExc followed by the Python exception name. These have the type; they are all class objects.
Standard Warning CategoriesAll standard Python warning categories are available as global variables whosenames are PyExc followed by the Python exception name. These have the type; they are all class objects. For completeness, here are allthe variables:C NamePython NameNotesPyExcWarning(1)PyExcBytesWarningPyExcDeprecationWarningPyExcFutureWarningPyExcImportWarningPyExcPendingDeprecationWarningPyExcRuntimeWarningPyExcSyntaxWarningPyExcUnicodeWarningPyExcUserWarningNotes:.This is a base class for other standard warning categories.
![]() Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |