Teks sumber — English
Terjemahan — Bahasa Indonesia
The functions described in this chapter will let you handle and raise Python exceptions. It is important to understand some of the basics of Python exception handling. It works somewhat like the POSIX :c:data:`errno` variable: there is a global indicator (per thread) of the last error that occurred. Most C API functions don't clear this on success, but will set it to indicate the cause of the error on failure. Most C API functions also return an error indicator, usually ``NULL`` if they are supposed to return a pointer, or ``-1`` if they return an integer (exception: the ``PyArg_*`` functions return ``1`` for success and ``0`` for failure).
When a function must fail because some function it called failed, it generally doesn't set the error indicator; the function it called already set it. It is responsible for either handling the error and clearing the exception or returning after cleaning up any resources it holds (such as object references or memory allocations); it should *not* continue normally if it is not prepared to handle the error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or carefully propagated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways.
Call this function **only** when the error indicator is set. Otherwise it will cause a fatal error!
This utility function prints a warning message to ``sys.stderr`` when an exception has been set but it is impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs in an :meth:`~object.__del__` method.
Use :func:`sys.unraisablehook`.
Gunakan :func:`sys.unraisablehook`.
Print the exception *value* with its traceback to :data:`sys.stderr`. If *value* has no traceback set, *tb* is used as its traceback. The first argument is ignored.
Use :c:func:`PyErr_DisplayException` instead.
These functions help you set the current thread's error indicator. For convenience, some of these functions will always return a ``NULL`` pointer for use in a ``return`` statement.
This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where *message* indicates that a built-in operation was invoked with an illegal argument. It is mostly for internal use.
Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if *filenameObject* is not ``NULL``, it is passed to the constructor of *type* as a third parameter. In the case of :exc:`OSError` exception, this is used to define the :attr:`!filename` attribute of the exception instance.
This is a convenience function to raise :exc:`OSError`. If called with *ierr* of ``0``, the error code returned by a call to :c:func:`!GetLastError` is used instead. It calls the Win32 function :c:func:`!FormatMessage` to retrieve the Windows description of error code given by *ierr* or :c:func:`!GetLastError`, then it constructs a :exc:`OSError` object with the :attr:`~OSError.winerror` attribute set to the error code, the :attr:`~OSError.strerror` attribute set to the corresponding error message (gotten from :c:func:`!FormatMessage`), and then calls ``PyErr_SetObject(PyExc_OSError, object)``. This function always returns ``NULL``.
Similar to :c:func:`PyErr_SetFromWindowsErr`, with the additional behavior that if *filename* is not ``NULL``, it is decoded from the filesystem encoding (:func:`os.fsdecode`) and passed to the constructor of :exc:`OSError` as a third parameter to be used to define the :attr:`!filename` attribute of the exception instance.
Similar to :c:func:`PyErr_SetExcFromWindowsErr`, with the additional behavior that if *filename* is not ``NULL``, it is passed to the constructor of :exc:`OSError` as a third parameter to be used to define the :attr:`!filename` attribute of the exception instance.
This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``, where *message* indicates that an internal operation (e.g. a Python/C API function) was invoked with an illegal argument. It is mostly for internal use.
Use these functions to issue warnings from C code. They mirror similar functions exported by the Python :mod:`warnings` module. They normally print a warning message to *sys.stderr*; however, it is also possible that the user has specified that warnings are to be turned into errors, and in that case they will raise an exception. It is also possible that the functions raise an exception because of a problem with the warning machinery. The return value is ``0`` if no exception is raised, or ``-1`` if an exception is raised. (It is not possible to determine whether a warning message is actually printed, nor what the reason is for the exception; this is intentional.) If an exception is raised, the caller should do its normal exception handling (for example, :c:func:`Py_DECREF` owned references and return an error value).
Function similar to :c:func:`PyErr_WarnEx`, but uses :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is an ASCII-encoded string.
Similar to :c:func:`PyErr_WarnExplicit`, but uses :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is an ASCII-encoded string.
Do not compare the return value to a specific exception; use :c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could easily fail since the exception may be an instance instead of a class, in the case of a class exception, or it may be a subclass of the expected exception.)
This function is used by code that needs to catch exceptions, or code that needs to save and restore the error indicator temporarily.
Use :c:func:`PyErr_GetRaisedException` instead.
Gunakan :c:func:`PyErr_GetRaisedException` sebagai gantinya.
This function is normally only used by legacy code that needs to catch exceptions or save and restore the error indicator temporarily.
Use :c:func:`PyErr_SetRaisedException` instead.
Gunakan :c:func:`PyErr_SetRaisedException` sebagai gantinya.
Set the error indicator from the three objects, *type*, *value*, and *traceback*, clearing the existing exception if one is set. If the objects are ``NULL``, the error indicator is cleared. Do not pass a ``NULL`` type and non-``NULL`` value or traceback. The exception type should be a class. Do not pass an invalid exception type or value. (Violating these rules will cause subtle problems later.) This call takes away a reference to each object: you must own a reference to each object before the call and after the call you no longer own these references. (If you don't understand this, don't use this function. I warned you.)
This function is normally only used by legacy code that needs to save and restore the error indicator temporarily. Use :c:func:`PyErr_Fetch` to save the current error indicator.
Use :c:func:`PyErr_GetRaisedException` instead, to avoid any possible de-normalization.
Gunakan :c:func:`PyErr_GetRaisedException` sebagai gantinya untuk menghindari segala kemungkinan denormalisasi.
Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is not an instance of the same class. This function can be used to instantiate the class in that case. If the values are already normalized, nothing happens. The delayed normalization is implemented to improve performance.
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use :c:func:`PyErr_SetHandledException` to restore or clear the exception state.
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use :c:func:`PyErr_GetHandledException` to get the exception state.
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the exception state.
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use :c:func:`PyErr_GetExcInfo` to read the exception state.
The ``type`` and ``traceback`` arguments are no longer used and can be NULL. The interpreter now derives them from the exception instance (the ``value`` argument). The function still ":term:`steals <steal>`" references of all three arguments.
For example, pressing :kbd:`Ctrl-C` causes a terminal to send the :py:data:`signal.SIGINT` signal. This function executes the corresponding Python signal handler, which, by default, raises the :exc:`KeyboardInterrupt` exception.
This function can be called by C code that sets up its own signal handling and wants Python signal handlers to be invoked as expected when an interruption is requested (for example when the user presses Ctrl-C to interrupt an operation).
The :attr:`~type.__module__` attribute of the new class is set to the first part (up to the last dot) of the *name* argument, and the class name is set to the last part (after the last dot). The *base* argument can be used to specify alternate base classes; it can either be only one class or a tuple of classes. The *dict* argument can be used to specify a dictionary of class variables and methods.
Same as :c:func:`PyErr_NewException`, except that the new exception class can easily be given a docstring: If *doc* is non-``NULL``, it will be used as the docstring for the exception class.
This was included in Python's C API by mistake and is not designed for use in extensions. For creating custom exception objects, use :c:func:`PyErr_NewException` or otherwise create a class inheriting from :c:data:`PyExc_BaseException`.
Set the traceback associated with the exception to *tb*. Use ``Py_None`` to clear it.
Set the context associated with the exception to *ctx*. Use ``NULL`` to clear it. There is no type check to make sure that *ctx* is an exception instance. This ":term:`steals <steal>`" a reference to *ctx*.
Return the cause (either an exception instance, or ``None``, set by ``raise ... from ...``) associated with the exception as a new reference, as accessible from Python through the :attr:`~BaseException.__cause__` attribute.
Set the cause associated with the exception to *cause*. Use ``NULL`` to clear it. There is no type check to make sure that *cause* is either an exception instance or ``None``. This ":term:`steals <steal>`" a reference to *cause*.
Implement part of the interpreter's implementation of :keyword:`!except*`. *orig* is the original exception that was caught, and *excs* is the list of the exceptions that need to be raised. This list contains the unhandled part of *orig*, if any, as well as the exceptions that were raised from the :keyword:`!except*` clauses (so they have a different traceback from *orig*) and those that were reraised (and have the same traceback as *orig*). Return the :exc:`ExceptionGroup` that needs to be reraised in the end, or ``None`` if there is nothing to reraise.
The following functions are used to create and modify Unicode exceptions from C.
These two functions provide a way to perform safe recursive calls at the C level, both in the core and in extension modules. They are needed if the recursive code does not necessarily invoke Python code (which tracks its recursion depth automatically). They are also not needed for *tp_call* implementations because the :ref:`call protocol <call>` takes care of recursion handling.
*where* should be a UTF-8 encoded string such as ``" in instance check"`` to be concatenated to the :exc:`RecursionError` message caused by the recursion depth limit.
The check is based on the remaining C stack space. Previously, a separate counter of C-level calls was used.
:exc:`ConnectionRefusedError`
:exc:`ConnectionRefusedError`
:c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`, :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`, :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`, :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`, :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`, :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`, :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError` and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`.
:c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`, :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`, :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`, :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`, :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`, :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`, :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError` dan :c:data:`PyExc_TimeoutError` diperkenalkan berikut :pep:`3151`.
These aliases used to be separate exception types.
:c:var:`!PyExc_WindowsError` is only defined on Windows; protect code that uses this by testing that the preprocessor macro ``MS_WINDOWS`` is defined.
:exc:`UserWarning`
:exc:`UserWarning`
This function is intended for use in crash scenarios such as signal handlers for SIGSEGV, where the interpreter may be in an inconsistent state. Given that it reads interpreter data structures that may be partially modified, the function might produce incomplete output or it may even crash itself.
If *current_tstate* is not ``NULL`` then it will be used to identify what the current thread is in the written output. If it is ``NULL`` then this function will identify the current thread using thread-specific storage. It is not an error if the function is unable to get the current Python thread state.
This function is meant to debug situations such as segfaults, fatal errors, and similar. It calls :c:func:`PyUnstable_DumpTraceback` for each thread. It only writes the tracebacks of the first *max_threads* threads, further output is truncated with the line ``...``. If *max_threads* is 0, the function will use a default value of 100 for the argument.