Chúng ta dùng constructor exception specific nhất phù hợp với issue cụ thể thay vì raise generic exceptions. Để catch specific exception của chúng ta, chúng ta phải catch tất cả specific exceptions khác subclass nó.
Chúng ta nên raise specific exceptions và handle cùng specific exceptions đó.
Để raise specific exceptions, chúng ta dùng statement raise như sau.
Ví dụ
import sys
try:
f = float('Tutorialspoint')
print(f)
raise ValueError
except Exception as err:
print(sys.exc_info())
Output
Chúng ta nhận được output sau:
(<type 'exceptions.ValueError'>, ValueError('could not convert string to float: Tutorialspoint',), <traceback object at 0x0000000002E33748>)
Chúng ta có thể raise error ngay cả với arguments như ví dụ sau:
Ví dụ
try:
raise ValueError('foo', 23)
except ValueError as e:
print(e.args)
Output
Chúng ta nhận được output sau:
('foo', 23)