Cara menggunakan python raise different exception
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 exceptionAs a Python developer you can choose to throw an exception if a condition occurs. Show
To throw (or raise) an exception, use the ExampleRaise an error and stop the program if x is lower than 0: x = -1 if x < 0: The You can define what kind of error to raise, and the text to print to the user. ExampleRaise a TypeError if x is not an integer: x = "hello" if not type(x) is int: Avoid raising a generic 0. To catch it, you'll have to catch all other more specific exceptions that subclass it.Problem 1: Hiding bugs
For example:
Problem 2: Won't catchAnd more specific catches won't catch the general exception:
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.
which also handily allows an arbitrary number of arguments to be passed to the constructor:
These arguments are accessed by the 2 attribute on the 0 object. For example:
prints
In Python 2.5, an actual 4 attribute was added to 5 in favor of encouraging users to subclass Exceptions and stop using 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 clauseWhen 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:
Don't modify your errors... but if you insist.You can preserve the stacktrace (and error value) with 9, but this is way more error prone and has compatibility problems between Python 2 and 3, prefer to use a bare 1 to re-raise.To explain - the 9 returns the type, value, and traceback.
This is the syntax in Python 2 - note this is not compatible with Python 3: 0If you want to, you can modify what happens with your new raise - e.g. setting new 2 for the instance: 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). 2In : 3Again: avoid manually manipulating tracebacks. It's and more error prone. And if you're using threading and 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 chainingIn Python 3, you can chain Exceptions, which preserve tracebacks: 4Be aware:
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: 5Only (2.4 and lower), you may still see people raising strings: 6In all modern versions, this will actually raise a 4, because you're not raising a 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 UsageI raise Exceptions to warn consumers of my API if they're using it incorrectly: 7Create your own error types when apropos
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: |