Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách catch ValueError dùng Exception trong Python?

ValueError được dùng khi function nhận giá trị có type đúng nhưng giá trị invalid.

Code cho trước có thể viết lại như sau để handle exception và tìm type của nó.

Ví dụ

import sys
try:
    n = int('magnolia')
except Exception as e:
    print(e)
    print(sys.exc_type)

Kết quả

invalid literal for int() with base 10: 'magnolia'
<type 'exceptions.ValueError'>