Agrument cho exception trong python 3.x

Xin chào
Mình có tham khảo tài liệu về exception trong python của tutorialpoint tại đây

https://www.tutorialspoint.com/python/python_exceptions.htm

Tài liệu này viết cho python 2.x. Đến đoạn agrument cho exception

Argument of an Exception

An exception can have an argument , which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception’s argument by supplying a variable in the except clause as follows −

try:
   You do your operations here;
   ......................
except ExceptionType, Argument:
   You can print value of Argument here...

If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.

This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.

#!/usr/bin/python

# Define a function here.
def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain numbers\n", Argument

# Call above function here.
temp_convert("xyz");

This produces the following result −
The argument does not contain numbers
invalid literal for int() with base 10: ‘xyz’

https://www.tutorialspoint.com/execute_python_online.php

Mình dùng Agrument trong py 3 mà bị lỗi
NameError: name 'Agrument' is not defined
code tương tự trên, chỉ có là agrument cho vào 1 tuple

Xin cảm ơn

Code của bạn đâu, có khi nào bạn gõ sai gì không

PS: nếu bạn gõ đúng thì vẫn có lỗi khác nhé. Hàm int() yêu cầu argument truyền vào là 1 string hoặc number, nhưng bạn lại truyền vào 1 tuple nên sẽ sinh ra exception là TypeError chứ không phải là ValueError nữa. Mà exception TypeError code trên không catch nên sẽ không thấy in đúng như kì vọng đâu

Update: python3 yêu cầu cú pháp khác 1 chút so với python2, do đó nếu bạn muốn lấy argument exception thì cú pháp phải được viết như bên dưới. Ngoài ra python2 cũng hỗ trợ cú pháp handle exception giống python3 nên để đảm bảo tương thích thì bạn nên dùng cú pháp handle exception của python3 để viết trên python2 thì tốt hơn.

try:
   ...
catch ValueError as Argument:
   print("The argument does not contain numbers\n", Argument)
2 Likes

À, mình hiểu rồi. Tks bạn, do mình đọc tài liệu py 2.x nhưng lại code py 3.x ,1 số chỗ thay cú pháp nên nhầm. :crazy_face:

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?