Pelokalan
Python ID
id en
Masuk
Proyek
tutorial__errors.po Berkas proyek · python-docs-id-3.14 · Bahasa Indonesia
Modul PO Hanya lihat
Teks sumber — English
Terjemahan — Bahasa Indonesia
Errors and Exceptions
Kesalahan *errors* dan Pengecualian *exceptions*
Until now error messages haven't been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: *syntax errors* and *exceptions*.
Sampai sekarang pesan kesalahan belum lebih dari yang disebutkan, tetapi jika Anda telah mencoba contohnya, Anda mungkin telah melihat beberapa. Ada (setidaknya) dua jenis kesalahan yang dapat dibedakan: *syntax errors* dan *exceptions*.
Exceptions
Pengecualian
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called *exceptions* and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here::
Bahkan jika suatu pernyataan atau ungkapan secara sintaksis benar, itu dapat menyebabkan kesalahan ketika suatu usaha dilakukan untuk mengeksekusinya. Kesalahan yang terdeteksi selama eksekusi disebut *exceptions* dan tidak fatal tanpa syarat: Anda akan segera belajar cara menanganinya dalam program Python. Namun, sebagian besar pengecualian tidak ditangani oleh program, dan menghasilkan pesan kesalahan seperti yang ditunjukkan di sini::
The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`. The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).
Baris terakhir dari pesan kesalahan menunjukkan apa yang terjadi. Pengecualian ada berbagai jenis yang berbeda, dan tipe dicetak sebagai bagian dari pesan: tipe dalam contoh adalah :exc:`ZeroDivisionError`, :exc:`NameError` dan :exc:`TypeError`. String yang dicetak sebagai jenis pengecualian adalah nama pengecualian bawaan yang terjadi. Ini berlaku untuk semua pengecualian bawaan, tetapi tidak harus sama untuk pengecualian yang dibuat pengguna (meskipun ini adalah konvensi yang bermanfaat). Nama pengecualian standar adalah pengidentifikasi bawaan (bukan kata kunci yang dipesan *reserved keyword*).
:ref:`bltin-exceptions` lists the built-in exceptions and their meanings.
:ref:`bltin-exceptions` memberikan daftar pengecualian bawaan dan artinya.
Handling Exceptions
Menangani Pengecualian
It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using :kbd:`Control-C` or whatever the operating system supports); note that a user-generated interruption is signalled by raising the :exc:`KeyboardInterrupt` exception. ::
Dimungkinkan untuk menulis program yang menangani pengecualian yang dipilih. Lihatlah contoh berikut, yang meminta masukan dari pengguna sampai integer yang valid telah dimasukkan, tetapi memungkinkan pengguna untuk menghentikan program (menggunakan :kbd:`Control-C` atau apa pun yang didukung sistem operasi); perhatikan bahwa gangguan yang dibuat pengguna ditandai dengan munculnya pengecualian :exc:`KeyboardInterrupt`. ::
A :keyword:`try` statement may have more than one *except clause*, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding *try clause*, not in other handlers of the same :keyword:`!try` statement. An *except clause* may name multiple exceptions, for example::
A class in an :keyword:`except` clause matches exceptions which are instances of the class itself or one of its derived classes (but not the other way around --- an *except clause* listing a derived class does not match instances of its base classes). For example, the following code will print B, C, D in that order::
The exception's :meth:`~object.__str__` output is printed as the last part ('detail') of the message for unhandled exceptions.
:exc:`BaseException` is the common base class of all exceptions. One of its subclasses, :exc:`Exception`, is the base class of all the non-fatal exceptions. Exceptions which are not subclasses of :exc:`Exception` are not typically handled, because they are used to indicate that the program should terminate. They include :exc:`SystemExit` which is raised by :meth:`sys.exit` and :exc:`KeyboardInterrupt` which is raised when a user wishes to interrupt the program.
:exc:`Exception` can be used as a wildcard that catches (almost) everything. However, it is good practice to be as specific as possible with the types of exceptions that we intend to handle, and to allow any unexpected exceptions to propagate on.
Exception handlers do not handle only exceptions that occur immediately in the *try clause*, but also those that occur inside functions that are called (even indirectly) in the *try clause*. For example::
Raising Exceptions
Memunculkan Pengecualian
This can be useful when you are transforming exceptions. For example::
Ini dapat berguna saat Anda mengubah pengecualian. Sebagai contoh::
For more information about chaining mechanics, see :ref:`bltin-exceptions`.
Untuk informasi lebih lanjut tentang mekanisme rantai, lihat :ref:`bltin-exceptions`.
User-defined Exceptions
Pengecualian yang Ditentukan Pengguna
Programs may name their own exceptions by creating a new exception class (see :ref:`tut-classes` for more about Python classes). Exceptions should typically be derived from the :exc:`Exception` class, either directly or indirectly.
Program dapat memberi nama pengecualian mereka sendiri dengan membuat kelas pengecualian baru (lihat :ref:`tut-classes` untuk informasi lebih lanjut tentang kelas Python). Pengecualian biasanya berasal dari kelas :exc:`Exception`, baik secara langsung atau tidak langsung.
Most exceptions are defined with names that end in "Error", similar to the naming of the standard exceptions.
Sebagian besar pengecualian didefinisikan dengan nama yang diakhiri dengan "Error", mirip dengan penamaan pengecualian standar.
Many standard modules define their own exceptions to report errors that may occur in functions they define.
If the :keyword:`!finally` clause executes a :keyword:`break`, :keyword:`continue` or :keyword:`return` statement, exceptions are not re-raised. This can be confusing and is therefore discouraged. From version 3.14 the compiler emits a :exc:`SyntaxWarning` for it (see :pep:`765`).
Raising and Handling Multiple Unrelated Exceptions
There are situations where it is necessary to report several exceptions that have occurred. This is often the case in concurrency frameworks, when several tasks may have failed in parallel, but there are also other use cases where it is desirable to continue execution and collect multiple errors rather than raise the first exception.
>>> def f(): ... excs = [OSError('error 1'), SystemError('error 2')] ... raise ExceptionGroup('there were problems', excs) ... >>> f() + Exception Group Traceback (most recent call last): | File "<stdin>", line 1, in <module> | f() | ~^^ | File "<stdin>", line 3, in f | raise ExceptionGroup('there were problems', excs) | ExceptionGroup: there were problems (2 sub-exceptions) +-+---------------- 1 ---------------- | OSError: error 1 +---------------- 2 ---------------- | SystemError: error 2 +------------------------------------ >>> try: ... f() ... except Exception as e: ... print(f'caught {type(e)}: {e}') ... caught <class 'ExceptionGroup'>: there were problems (2 sub-exceptions) >>>
By using ``except*`` instead of ``except``, we can selectively handle only the exceptions in the group that match a certain type. In the following example, which shows a nested exception group, each ``except*`` clause extracts from the group exceptions of a certain type while letting all other exceptions propagate to other clauses and eventually to be reraised. ::
Note that the exceptions nested in an exception group must be instances, not types. This is because in practice the exceptions would typically be ones that have already been raised and caught by the program, along the following pattern::
Enriching Exceptions with Notes
When an exception is created in order to be raised, it is usually initialized with information that describes the error that has occurred. There are cases where it is useful to add information after the exception was caught. For this purpose, exceptions have a method ``add_note(note)`` that accepts a string and adds it to the exception's notes list. The standard traceback rendering includes all notes, in the order they were added, after the exception. ::
For example, when collecting exceptions into an exception group, we may want to add context information for the individual errors. In the following each exception in the group has a note indicating when this error has occurred. ::
>>> def f(): ... raise OSError('operation failed') ... >>> excs = [] >>> for i in range(3): ... try: ... f() ... except Exception as e: ... e.add_note(f'Happened in Iteration {i+1}') ... excs.append(e) ... >>> raise ExceptionGroup('We have some problems', excs) + Exception Group Traceback (most recent call last): | File "<stdin>", line 1, in <module> | raise ExceptionGroup('We have some problems', excs) | ExceptionGroup: We have some problems (3 sub-exceptions) +-+---------------- 1 ---------------- | Traceback (most recent call last): | File "<stdin>", line 3, in <module> | f() | ~^^ | File "<stdin>", line 2, in f | raise OSError('operation failed') | OSError: operation failed | Happened in Iteration 1 +---------------- 2 ---------------- | Traceback (most recent call last): | File "<stdin>", line 3, in <module> | f() | ~^^ | File "<stdin>", line 2, in f | raise OSError('operation failed') | OSError: operation failed | Happened in Iteration 2 +---------------- 3 ---------------- | Traceback (most recent call last): | File "<stdin>", line 3, in <module> | f() | ~^^ | File "<stdin>", line 2, in f | raise OSError('operation failed') | OSError: operation failed | Happened in Iteration 3 +------------------------------------ >>>