如果用戶在輸入中輸入字串而不是數字,則用戶定義的例外在這里我將類用于用戶定義的例外,我知道如果我使用 ==> except Exception: 它會起作用,但我想使用用戶定義的例外 ==>除了錯誤
class error(Exception):
pass
class b(error):
try:
age = int(input("Enter your age:\n>>"))
if(age >= 18):
print("You are Eligible for Voting")
elif(age < 18):
print("You are not Eligible for Voting")
else:
raise error
except error: # except Exception: --> it works
print("Invalid input")
print("Enter a number as your age")
obj = b()
輸出:-
Enter your age:
>> sdsd
Traceback (most recent call last):
File "c:\Users\HP\OneDrive\Desktop\All Desktop <br>apps\Python\Python_Programs\exception_handling.py", line 6, in <module>
class b(error):
File "c:\Users\HP\OneDrive\Desktop\All Desktop apps\Python\Python_Programs\exception_handling.py", line 8, in b
age = int(input("Enter your age:\n>>"))
ValueError: invalid literal for int() with base 10: 'sdsd'

uj5u.com熱心網友回復:
當你輸入 'sdsd' 時,你會從函式 int() 中得到一個 ValueError:
age = int(input("Enter your age:\n>>"))
因此,當您嘗試捕獲錯誤(您定義的)時,它不起作用。
ValueError: invalid literal for int() with base 10: 'sdsd'
ValueError 是 Exception 的子類,當你捕捉到 Exception 時,你的代碼可以捕捉到這個 ValueError,所以它可以作業。
uj5u.com熱心網友回復:
如果例外是給定子句的例外類的實體或其子類,則該except子句僅捕獲例外。except
在您的情況下,建構式在將非整數格式的字串作為輸入時int引發,并且由于是該類的子類,您可以使用. 但是您無法捕捉到它,因為它不是您的用戶定義類的子類。ValueErrorValueErrorExceptionexcept Exceptionexcept errorValueErrorerror
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489148.html
