Hướng dẫn raise exception without try python - tăng ngoại lệ mà không cần thử python

Làm cách nào để ném/nâng một ngoại lệ theo cách thủ công trong Python?

Sử dụng hàm tạo ngoại lệ cụ thể nhất phù hợp về mặt ngữ nghĩa của bạn.

Hãy cụ thể trong tin nhắn của bạn, ví dụ:

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

Đừng nâng cao các trường hợp ngoại lệ chung

Tránh nâng cao

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 chung. Để bắt nó, bạn sẽ phải nắm bắt tất cả các trường hợp ngoại lệ cụ thể khác mà phân lớp nó.

Bài 1: ẩn lỗi

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

Ví dụ:

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

Bài 2: Không bắt được

Và các sản phẩm khai thác cụ thể hơn sẽ không bắt được ngoại lệ chung:

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

Thực tiễn tốt nhất: Tuyên bố 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

Thay vào đó, hãy sử dụng hàm tạo ngoại lệ cụ thể nhất phù hợp về mặt ngữ nghĩa của bạn.

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

cũng cho phép một số lượng đối số tùy ý được chuyển cho hàm tạo:

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

Các đối số này được truy cập bởi thuộc tính

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 trên đối tượng
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. Ví dụ:

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

bản in

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

Trong Python 2.5, một thuộc tính

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 thực tế đã được thêm vào
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 ủng hộ việc khuyến khích người dùng các ngoại lệ của lớp con và ngừng sử dụng
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, nhưng việc giới thiệu
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 và việc không khấu hao ban đầu của ARGS đã được rút lại.

Thực tiễn tốt nhất: mệnh đề 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

Khi bên trong một mệnh đề ngoại trừ, ví dụ, bạn có thể muốn đăng nhập rằng một loại lỗi cụ thể đã xảy ra, và sau đó chuyển đổi lại. Cách tốt nhất để làm điều này trong khi bảo tồn dấu vết ngăn xếp là sử dụng tuyên bố nâng cao. Ví dụ:

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!

Đừng sửa đổi lỗi của bạn ... nhưng nếu bạn khăng khăng.

Bạn có thể bảo toàn ngăn xếp (và giá trị lỗi) với

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, nhưng đây là cách dễ bị lỗi hơn và có vấn đề tương thích giữa Python 2 và 3, thích sử dụng
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 để truy xuất lại.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.

Để giải thích -

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 trả về loại, giá trị và dấu vết.

type, value, traceback = sys.exc_info()

Đây là cú pháp trong Python 2 - Lưu ý Điều này không tương thích với Python 3:

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

Nếu bạn muốn, bạn có thể sửa đổi những gì xảy ra với mức tăng mới của bạn - ví dụ: Đặt mới

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 cho phiên bản:

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

Và chúng tôi đã bảo tồn toàn bộ dấu vết trong khi sửa đổi các cuộc tranh luận. Lưu ý rằng đây không phải là một thông lệ tốt nhất và nó là cú pháp không hợp lệ trong Python 3 (khiến việc giữ khả năng tương thích khó hoạt động hơn nhiều).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.
2

Trong Python 3:

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

Một lần nữa: Tránh thao tác thủ công theo dõi. Nó kém hiệu quả và dễ bị lỗi hơn. Và nếu bạn đang sử dụng luồng và

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, bạn thậm chí có thể nhận được dấu vết sai (đặc biệt là nếu bạn đang sử dụng xử lý ngoại lệ cho luồng điều khiển - mà cá nhân tôi có xu hướng tránh.)

Python 3, chuỗi ngoại lệ

Trong Python 3, bạn có thể chuỗi ngoại lệ, lưu giữ các dấu vết:

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

Nhận biết:

  • Điều này cho phép thay đổi loại lỗi được nêu ra và
  • Điều này không tương thích với Python 2.

Phương pháp không dùng nữa:

Những điều này có thể dễ dàng ẩn và thậm chí đi vào mã sản xuất. Bạn muốn nâng cao một ngoại lệ, và làm chúng sẽ tăng một ngoại lệ, nhưng không phải là ý định!but not the one intended!

Hợp lệ trong Python 2, nhưng không phải trong Python 3 như sau:

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

Chỉ có giá trị trong các phiên bản Python cũ hơn nhiều (2.4 trở xuống), bạn vẫn có thể thấy mọi người nâng chuỗi:

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

Trong tất cả các phiên bản hiện đại, điều này thực sự sẽ tăng

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, bởi vì bạn không phải là loại
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. Nếu bạn không kiểm tra ngoại lệ đúng và không có người đánh giá biết về vấn đề này, nó có thể được đưa vào sản xuất.

Ví dụ sử dụng

Tôi nêu ra các ngoại lệ để cảnh báo người tiêu dùng API của mình nếu họ sử dụng nó không chính xác:

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

Tạo các loại lỗi của riêng bạn khi apropos

"Tôi muốn có một lỗi có chủ đích, để nó đi vào ngoại trừ"

Bạn có thể tạo các loại lỗi của riêng mình, nếu bạn muốn chỉ ra điều gì đó cụ thể là sai với ứng dụng của bạn, chỉ cần phân lớp điểm thích hợp trong hệ thống phân cấp ngoại lệ:

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

và cách sử dụng:

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

Tôi có thể sử dụng ngoại trừ mà không cần thử trong Python không?

Chặn để xử lý các ngoại lệ trong Python.Nó cho phép chúng tôi áp dụng một số hoạt động đặc biệt khi có điều gì đó không ổn.Nếu tình huống thỏa mãn các điều kiện trên, bạn không phải sử dụng thử ... ngoại trừ ... để xử lý các ngoại lệ.If the situation satisfies the above conditions, you don't have to use try ... except ... to handle the exceptions.

Có phải thực hành tốt để sử dụng thử ngoại trừ trong Python?

Lý do sử dụng thử/ngoại trừ là khi bạn có một khối mã để thực thi đôi khi sẽ chạy chính xác và đôi khi không, tùy thuộc vào các điều kiện bạn không thể thấy trước tại thời điểm bạn viết mã.when you have a code block to execute that will sometimes run correctly and sometimes not, depending on conditions you can't foresee at the time you're writing the code.

Có phải một ngoại lệ dừng thực thi Python?

Khi một ngoại lệ được nêu ra, không có câu lệnh nào trong khối mã hiện tại được thực thi.Trừ khi ngoại lệ được xử lý (được mô tả bên dưới), trình thông dịch sẽ trở lại trực tiếp vào vòng lặp in-eval tương tác hoặc chấm dứt hoàn toàn nếu Python được bắt đầu bằng đối số tệp.