Exception
Kelas dasar untuk semua pengecualian / exception StopIteration
Dibesarkan ketika metode [iterator] berikutnya dari iterator tidak mengarah ke objek apa pun. SystemExit
Dibesarkan oleh fungsi sys.exit []. StandardError
Kelas dasar untuk semua pengecualian built-in kecuali StopIteration dan SystemExit. ArithmeticError
Kelas dasar untuk semua kesalahan yang terjadi untuk perhitungan numerik. OverflowError
Dibesarkan saat perhitungan melebihi batas maksimum untuk tipe numerik. FloatingPointError
Dibesarkan saat perhitungan floating point gagal. ZeroDivisonError
Dibesarkan saat pembagian atau modulo nol dilakukan untuk semua tipe numerik. AssertionError
Dibesarkan jika terjadi kegagalan pernyataan Assert. AttributeError
Dibesarkan jika terjadi kegagalan referensi atribut atau penugasan. StopIteration
0 Dibesarkan bila tidak ada input dari fungsi raw_input [] atau input [] dan akhir file tercapai. StopIteration
1 Dibesarkan saat sebuah pernyataan impor gagal. StopIteration
2 Dibesarkan saat pengguna menyela eksekusi program, biasanya dengan menekan Ctrl + c. StopIteration
3 Kelas dasar untuk semua kesalahan pencarian. StopIteration
4 Dibesarkan saat sebuah indeks tidak ditemukan secara berurutan. StopIteration
5 Dibesarkan saat kunci yang ditentukan tidak ditemukan dalam kamus. StopIteration
6 Dibesarkan saat pengenal tidak ditemukan di namespace lokal atau global. StopIteration
7 Dibesarkan saat mencoba mengakses variabel lokal dalam suatu fungsi atau metode namun tidak ada nilai yang ditugaskan padanya. StopIteration
8 Kelas dasar untuk semua pengecualian yang terjadi di luar lingkungan Python. StopIteration
9 Dibesarkan saat operasi input / output gagal, seperti pernyataan cetak atau fungsi open [] saat mencoba membuka file yang tidak ada. SystemExit
0 Dibangkitkan untuk kesalahan terkait sistem operasi. SystemExit
1 Dibesarkan saat ada kesalahan dengan sintaks Python. SystemExit
2 Dibesarkan saat indentasi tidak ditentukan dengan benar. SystemExit
3 Dibesarkan saat penafsir menemukan masalah internal, namun bila kesalahan ini ditemui juru bahasa Python tidak keluar. SystemExit
Dibesarkan saat juru bahasa Python berhenti dengan menggunakan fungsi sys.exit []. Jika tidak ditangani dalam kode, menyebabkan penafsir untuk keluar. SystemExit
5 Dibesarkan saat operasi atau fungsi dicoba yang tidak valid untuk tipe data yang ditentukan. SystemExit
6 Dibesarkan ketika fungsi bawaan untuk tipe data memiliki jenis argumen yang valid, namun argumen tersebut memiliki nilai yang tidak valid yang ditentukan. SystemExit
7 Dibesarkan saat kesalahan yang dihasilkan tidak termasuk dalam kategori apa pun. SystemExit
8 Dibesarkan ketika metode abstrak yang perlu diimplementasikan di kelas warisan sebenarnya tidak dilaksanakan. Raise an exception
As a Python developer you can choose to throw an exception if a condition occurs.
To throw [or raise] an exception, use the raise
keyword.
Example
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception["Sorry, no numbers below zero"]
The raise
keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
Example
Raise a TypeError if x is not an integer:
x = "hello"
if not type[x] is int:
raise TypeError["Only integers are allowed"]
Avoid raising a generic
def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
0. To catch it, you'll have to catch all other more specific exceptions that subclass it.Problem 1: Hiding bugs
raise Exception['I know Python!'] # Don't! If you catch, likely to hide bugs.
For example:
def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
Problem 2: Won't catch
And more specific catches won't catch the general exception:
def demo_no_catch[]:
try:
raise Exception['general exceptions not caught by specific handling']
except ValueError as e:
print['we will not catch exception: Exception']
>>> demo_no_catch[]
Traceback [most recent call last]:
File "", line 1, in
File "", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
Best Practices: def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
1 statement
def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
.
raise ValueError['A very specific bad thing happened']
which also handily allows an arbitrary number of arguments to be passed to the constructor:
raise ValueError['A very specific bad thing happened', 'foo', 'bar', 'baz']
These arguments are accessed by the
def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
2 attribute on the def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
0 object. For example:try:
some_code_that_may_raise_our_value_error[]
except ValueError as err:
print[err.args]
prints
['message', 'foo', 'bar', 'baz']
In Python 2.5, an actual
def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
4 attribute was added to def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
5 in favor of encouraging users to subclass Exceptions and stop using def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
2, but .Best Practices: def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
8 clause
def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
When inside an except clause, you might want to, for example, log that a specific type of error happened, and then re-raise. The best way to do this while preserving the stack trace is to use a bare raise statement. For example:
logger = logging.getLogger[__name__]
try:
do_something_in_app_that_breaks_easily[]
except AppError as error:
logger.error[error]
raise # just this!
# raise AppError # Don't do this, you'll lose the stack trace!
Don't modify your errors... but if you insist.
You can preserve the stacktrace [and error value] with
def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
9, but this is way more error prone and has compatibility problems between Python 2 and 3, prefer to use a bare def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
1 to re-raise.To explain - the
def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
9 returns the type, value, and traceback.type, value, traceback = sys.exc_info[]
This is the syntax in Python 2 - note this is not compatible with Python 3:
raise Exception['I know Python!'] # Don't! If you catch, likely to hide bugs.
0If you want to, you can modify what happens with your new raise - e.g. setting new
def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
2 for the instance:raise Exception['I know Python!'] # Don't! If you catch, likely to hide bugs.
1And we have preserved the whole traceback while modifying the args. Note that this is not a best practice and it is invalid syntax in Python 3 [making keeping compatibility much harder to work around].
raise Exception['I know Python!'] # Don't! If you catch, likely to hide bugs.
2In :
raise Exception['I know Python!'] # Don't! If you catch, likely to hide bugs.
3Again: avoid manually manipulating tracebacks. It's and more error prone. And if you're using threading and
def demo_no_catch[]:
try:
raise Exception['general exceptions not caught by specific handling']
except ValueError as e:
print['we will not catch exception: Exception']
>>> demo_no_catch[]
Traceback [most recent call last]:
File "", line 1, in
File "", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
3 you may even get the wrong traceback [especially if you're using exception handling for control flow - which I'd personally tend to avoid.]Python 3, Exception chaining
In Python 3, you can chain Exceptions, which preserve tracebacks:
raise Exception['I know Python!'] # Don't! If you catch, likely to hide bugs.
4Be aware:
- this does allow changing the error type raised, and
- this is not compatible with Python 2.
Deprecated Methods:
These can easily hide and even get into production code. You want to raise an exception, and doing them will raise an exception, but not the one intended!
Valid in Python 2, but not in Python 3 is the following:
raise Exception['I know Python!'] # Don't! If you catch, likely to hide bugs.
5Only [2.4 and lower], you may still see people raising strings:
raise Exception['I know Python!'] # Don't! If you catch, likely to hide bugs.
6In all modern versions, this will actually raise a
def demo_no_catch[]:
try:
raise Exception['general exceptions not caught by specific handling']
except ValueError as e:
print['we will not catch exception: Exception']
>>> demo_no_catch[]
Traceback [most recent call last]:
File "", line 1, in
File "", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
4, because you're not raising a def demo_bad_catch[]:
try:
raise ValueError['Represents a hidden bug, do not catch this']
raise Exception['This is the exception you expect to handle']
except Exception as error:
print['Caught this error: ' + repr[error]]
>>> demo_bad_catch[]
Caught this error: ValueError['Represents a hidden bug, do not catch this',]
5 type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production.Example Usage
I raise Exceptions to warn consumers of my API if they're using it incorrectly:
raise Exception['I know Python!'] # Don't! If you catch, likely to hide bugs.
7Create your own error types when apropos
"I want to make an error on purpose, so that it would go into the except"
You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy: