Apa yang menaikkan pengecualian di python menjelaskannya menggunakan contoh?

Hindari meningkatkan

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 generik. Untuk menangkapnya, Anda harus menangkap semua pengecualian lain yang lebih spesifik yang mensubklasifikasikannya

Masalah 1. Menyembunyikan bug

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
_

Sebagai contoh

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',)

Masalah 2. Tidak akan menangkap

Dan tangkapan yang lebih spesifik tidak akan menangkap pengecualian umum

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

Praktik terbaik. 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 pernyataan

.

raise ValueError('A very specific bad thing happened')

yang juga dengan mudah memungkinkan sejumlah argumen untuk diteruskan ke konstruktor

raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 
_

Argumen ini diakses oleh atribut

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 pada objek
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. Sebagai contoh

try:
    some_code_that_may_raise_our_value_error()
except ValueError as err:
    print(err.args)
_

cetakan

('message', 'foo', 'bar', 'baz')    

Dalam Python2. 5, atribut

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 yang sebenarnya ditambahkan ke
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 untuk mendorong pengguna ke Pengecualian subkelas dan berhenti menggunakan
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, tetapi

Praktik terbaik. 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 klausa

Saat berada di dalam klausa kecuali, Anda mungkin ingin, misalnya, mencatat bahwa jenis kesalahan tertentu terjadi, lalu menaikkan kembali. Cara terbaik untuk melakukannya sambil mempertahankan pelacakan tumpukan adalah dengan menggunakan pernyataan bare raise. Sebagai contoh

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!

Jangan ubah kesalahan Anda. tetapi jika Anda bersikeras

Anda dapat mempertahankan stacktrace (dan nilai kesalahan) dengan

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, tetapi ini jauh lebih rawan kesalahan dan memiliki masalah kompatibilitas antara Python 2 dan 3, lebih suka menggunakan
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 kosong untuk menaikkan kembali

Untuk menjelaskan -

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 mengembalikan tipe, nilai, dan traceback

type, value, traceback = sys.exc_info()

Ini adalah sintaks di Python 2 - perhatikan bahwa ini tidak kompatibel dengan Python 3

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
_0

Jika mau, Anda dapat mengubah apa yang terjadi dengan kenaikan gaji baru Anda - mis. g. pengaturan baru

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 untuk contoh

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
_1

Dan kami telah mempertahankan seluruh traceback sambil memodifikasi args. Perhatikan bahwa ini bukan praktik terbaik dan ini adalah sintaks yang tidak valid di Python 3 (membuat menjaga kompatibilitas jauh lebih sulit untuk dikerjakan)

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
_2

Di dalam

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
_3

Lagi. hindari manipulasi traceback secara manual. Ini dan lebih rawan kesalahan. Dan jika Anda menggunakan threading dan

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 Anda bahkan mungkin mendapatkan traceback yang salah (terutama jika Anda menggunakan penanganan pengecualian untuk aliran kontrol - yang secara pribadi cenderung saya hindari. )

Python 3, Pengecualian berantai

Di Python 3, Anda dapat merangkai Pengecualian, yang mempertahankan traceback

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
_4

Waspadalah

  • ini memungkinkan mengubah jenis kesalahan yang dimunculkan, dan
  • ini tidak kompatibel dengan Python 2

Metode yang Tidak Digunakan Lagi

Ini dapat dengan mudah disembunyikan dan bahkan masuk ke kode produksi. Anda ingin mengajukan pengecualian, dan melakukannya akan memunculkan pengecualian, tetapi bukan yang dimaksud

Valid di Python 2, tetapi tidak di Python 3 adalah sebagai berikut

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
_5

Hanya 2. 4 dan lebih rendah), Anda mungkin masih melihat orang mengangkat tali

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
_6

Di semua versi modern, ini sebenarnya akan memunculkan

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, karena Anda tidak memunculkan tipe
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. Jika Anda tidak memeriksa pengecualian yang tepat dan tidak memiliki peninjau yang mengetahui masalah tersebut, itu bisa masuk ke produksi

Contoh Penggunaan

Saya mengajukan Pengecualian untuk memperingatkan konsumen tentang API saya jika mereka salah menggunakannya

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
_7

Buat jenis kesalahan Anda sendiri saat itu juga

"Saya ingin membuat kesalahan dengan sengaja, sehingga akan masuk ke kecuali"

Anda dapat membuat jenis kesalahan Anda sendiri, jika Anda ingin menunjukkan ada sesuatu yang salah dengan aplikasi Anda, cukup subkelaskan titik yang sesuai dalam hierarki pengecualian

Apa pengecualian peningkatan di Python dengan contoh?

Contoh. Tingkatkan kesalahan dan hentikan program jika x lebih rendah dari 0 . x = -1. jika x < 0. raise Exception("Maaf, tidak ada angka di bawah nol")

Apa itu pengecualian kenaikan?

Memunculkan pengecualian adalah teknik untuk menginterupsi aliran normal eksekusi dalam suatu program, menandakan bahwa beberapa keadaan luar biasa telah muncul, dan kembali langsung ke bagian terlampir dari program yang dirancang untuk bereaksi terhadap keadaan tersebut.

Mengapa kami memunculkan pengecualian dengan Python?

Terkadang Anda ingin Python melontarkan pengecualian khusus untuk penanganan kesalahan. Anda dapat melakukan ini dengan memeriksa suatu kondisi dan menaikkan pengecualian, jika kondisinya Benar. Pengecualian yang dimunculkan biasanya memperingatkan pengguna atau aplikasi pemanggil .

Bagaimana Anda menangani peningkatan pengecualian dengan Python?

Untuk menangani pengecualian, kami telah memasukkan kode, result = pembilang/penyebut di dalam blok try . Sekarang ketika pengecualian terjadi, sisa kode di dalam blok percobaan akan dilewati. Kecuali blok menangkap pengecualian dan pernyataan di dalam kecuali blok dieksekusi.