Hướng dẫn how do you manually raise an exception in python? - làm cách nào để bạn nâng một ngoại lệ theo cách thủ công trong 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

Làm cách nào để nâng cao một ngoại lệ?

Ném các ngoại lệ theo cách thủ công Có hai loại ngoại lệ được xác định và xác định trước mỗi ngoại lệ được đại diện bởi một lớp và kế thừa lớp có thể ném. Để ném một ngoại lệ rõ ràng, bạn cần khởi tạo lớp của nó và ném đối tượng của nó bằng từ khóa ném.instantiate the class of it and throw its object using the throw keyword.

Làm thế nào để bạn tăng một ngoại lệ trong Python?

Bắt các trường hợp ngoại lệ trong Python trong Python, các ngoại lệ có thể được xử lý bằng cách sử dụng câu lệnh thử.Hoạt động quan trọng có thể tăng một ngoại lệ được đặt bên trong mệnh đề thử.Mã xử lý các ngoại lệ được viết trong mệnh đề ngoại trừ.using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

Chúng ta có thể tăng ngoại lệ mà không cần thử trong Python không?

Khối cuối cùng của người Viking chạy về việc có hay không mã của Block Try có làm tăng một ngoại lệ hay không.Nếu có một ngoại lệ, mã trong khối tương ứng, ngoại trừ, ngoại trừ sẽ chạy và sau đó mã trong khối cuối cùng sẽ chạy.. If there's an exception, the code in the corresponding “except” block will run, and then the code in the “finally” block will run.

Làm thế nào để bạn tăng lương trong Python?

Từ khóa RAISE được sử dụng để nâng cao một ngoại lệ.Bạn có thể xác định loại lỗi nào để nêu và văn bản để in cho người dùng.. You can define what kind of error to raise, and the text to print to the user.