Hướng dẫn how do you give a raise in python? - Làm thế nào để bạn tăng lương cho trăn?

Python nâng cao từ khóa được sử dụng để tăng các ngoại lệ hoặc lỗi. Từ khóa RAFIC gây ra lỗi và dừng luồng điều khiển của chương trình. Nó được sử dụng để đưa ra ngoại lệ hiện tại trong một trình xử lý ngoại lệ để nó có thể được xử lý thêm trên ngăn xếp cuộc gọi. is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.

Cú pháp của từ khóa nâng cao:

REAVE & NBSP; {name_of_ the_ Except

Cách cơ bản để gây ra lỗi là:

Nâng cao ngoại lệ (văn bản người dùng của người dùng ”)

Example:

Trong mã dưới đây, chúng tôi kiểm tra xem một số nguyên chẵn hoặc lẻ. Nếu số nguyên là lẻ, một ngoại lệ được nâng lên. & nbsp;

Input:

Python3

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

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',)
3
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
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
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',)
6
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',)
7
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
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
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
03030

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
1
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
2
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
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
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
5

Output:

Hướng dẫn how do you give a raise in python? - Làm thế nào để bạn tăng lương cho trăn?

Trong khi nêu ra một lỗi, chúng ta cũng có thể loại lỗi nào chúng ta cần nêu ra và nếu cần in văn bản.

Syntax: 

Nâng cao loại

Example:

Trong mã dưới đây, chúng tôi đã thử thay đổi chuỗi ‘Apple, & NBSP; được gán cho S thành Integer và viết một điều khoản Excet Try-Except để nâng cao giá trị. Từ khóa RAFIC làm tăng lỗi giá trị với thông báo Chuỗi Chuỗi có thể được thay đổi thành một số nguyên.

Input:

Python3

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
6
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
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
8

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
9
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
0

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
1
raise ValueError('A very specific bad thing happened')
2
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
raise ValueError('A very specific bad thing happened')
4
raise ValueError('A very specific bad thing happened')
5

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

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
1
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
2
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 
0
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 
1
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
5

Đầu ra::

Hướng dẫn how do you give a raise in python? - Làm thế nào để bạn tăng lương cho trăn?

Nâng cao một ngoại lệ mà không chỉ định lớp ngoại lệ

Khi chúng tôi sử dụng từ khóa Raise, không có sự ép buộc nào để đưa ra một lớp ngoại lệ cùng với nó. Khi chúng tôi không đưa ra bất kỳ tên lớp ngoại lệ nào với từ khóa RAISE, nó sẽ xuất hiện ngoại lệ xảy ra lần cuối.

Example:

Trong mã trên, chúng tôi đã thử thay đổi chuỗi ‘Apple, thành Integer và đã viết một điều khoản Except thử để nâng cao giá trị. Mã này giống như trước đây ngoại trừ việc chúng tôi không cung cấp một lớp ngoại lệ, nó lại xuất hiện ngoại lệ xảy ra lần cuối.

Input:

Python3

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
6
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
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
8

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
9
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
0

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
1
raise ValueError('A very specific bad thing happened')
2
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
raise ValueError('A very specific bad thing happened')
4
raise ValueError('A very specific bad thing happened')
5

raise ValueError('A very specific bad thing happened')
6
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
0

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
1
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
2

Output:

Hướng dẫn how do you give a raise in python? - Làm thế nào để bạn tăng lương cho trăn?

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

  • 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
    
    1
    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
    
    2
    raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 
    
    0
    raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 
    
    1
    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
    
    5
  • Đầu ra:
  • Nâng cao một ngoại lệ mà không chỉ định lớp ngoại lệ
  • Khi chúng tôi sử dụng từ khóa Raise, không có sự ép buộc nào để đưa ra một lớp ngoại lệ cùng với nó. Khi chúng tôi không đưa ra bất kỳ tên lớp ngoại lệ nào với từ khóa RAISE, nó sẽ xuất hiện ngoại lệ xảy ra lần cuối.

Từ khóa Python


Thí dụ

Tăng lỗi và dừng chương trình nếu X thấp hơn 0:

x = -1

Nếu x <0: & nbsp; Tăng ngoại lệ ("Xin lỗi, không có số dưới 0")
  raise Exception("Sorry, no numbers below zero")

Hãy tự mình thử »


Định nghĩa và cách sử dụng

Từ khó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
2 được sử dụng để nâng cao 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.


Nhiều ví dụ hơn

Thí dụ

Tăng lỗi và dừng chương trình nếu X thấp hơn 0:

x = -1

Nếu x <0: & nbsp; Tăng ngoại lệ ("Xin lỗi, không có số dưới 0")
  raise TypeError("Only integers are allowed")

Hãy tự mình thử »


Từ khóa 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

try:
    some_code_that_may_raise_our_value_error()
except ValueError as err:
    print(err.args)
8 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_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 2

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

('message', 'foo', 'bar', 'baz')    
0 trên đối tượng
try:
    some_code_that_may_raise_our_value_error()
except ValueError as err:
    print(err.args)
8. 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

('message', 'foo', 'bar', 'baz')    
2 thực tế đã được thêm vào
('message', 'foo', 'bar', 'baz')    
3 có lợi cho việc khuyến khích người dùng các trường hợp ngoại lệ của lớp con và ngừng sử dụng
('message', 'foo', 'bar', 'baz')    
0, nhưng việc giới thiệu
('message', 'foo', 'bar', 'baz')    
2 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 đề raise ValueError('A very specific bad thing happened') 6

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

('message', 'foo', 'bar', 'baz')    
7, 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_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
2 để 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_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
2 to re-raise.

Để giải thích -

('message', 'foo', 'bar', 'baz')    
7 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

('message', 'foo', 'bar', 'baz')    
0 mới 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à

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!
1, 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

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!
2, bởi vì bạn không phải là loại
('message', 'foo', 'bar', 'baz')    
3. 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

Nâng cao () làm gì 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.raise an exception. You can define what kind of error to raise, and the text to print to the user.

Làm thế nào để bạn nêu ra một lỗi loại trong Python?

Là một nhà phát triển Python, bạn có thể chọn ném một ngoại lệ nếu xảy ra điều kiện.Để ném (hoặc nâng cao) một ngoại lệ, hãy sử dụng từ khóa nâng cao.use the raise keyword.

Tôi có thể nuôi và trả lại Python không?

Bạn không thể nâng cao và trả lại, nhưng bạn có thể trả về nhiều giá trị, trong đó giá trị đầu tiên giống như những gì bạn hiện đang sử dụng và thứ hai cho biết một ngoại lệ có phát sinh trả về đúng hay không.exc_info () == (không có, không có, không có) hoặc một cái gì đó tương tự nhưng phù hợp hơn với bối cảnh. , but you could return multiple values, where the first is the same as what you're currently using, and the second indicates if an exception arose return True, sys. exc_info() == (None, None, None) or something similar but better suited to context.

Làm thế nào để tôi thực hiện các ngoại lệ theo cách thủ công?

Ném các ngoại lệ theo cách thủ công để ném một ngoại lệ rõ ràng, bạn cần phải 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.