0
有很多內置的異常類,如EOFError,KeyboardInterrupt等,但是我怎樣才能創建自己的異常類。例如,如果我想保持約束,那麼用戶應該輸入一個長度最少爲3的字符串。如何在Python中實現用戶定義的異常?
有很多內置的異常類,如EOFError,KeyboardInterrupt等,但是我怎樣才能創建自己的異常類。例如,如果我想保持約束,那麼用戶應該輸入一個長度最少爲3的字符串。如何在Python中實現用戶定義的異常?
檢查此代碼爲用戶定義的異常:
class ShortInputException(Exception):
def __init__(self,length,atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter some text: ')
if len(text) < 3:
raise ShortInputException(len(text),3)
except EOFError:
print('It is end of file.')
except ShortInputException as ex:
print('ShortInputException: You entered {0} length long text. Expected text size is {1}'.format(ex.length,ex.atleast))
except KeyboardInterrupt:
print('You interrupted the program execution.')
else:
print('No exception/s raised.')
print('You entered: {0}'.format(text))
您可以在類定義的異常或者,也可以在下面創建自己的異常類。
/** * 定義延伸異常 */
類Your_Exception延伸您的異常類異常:
// redefine exception with a message
public function __construct($message, $code = 0, Exception $previous = null):
//Call Parent constructor
parent::__construct($message, $code, $previous);
// custom string representation of object
public function __to_String():
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
public function user_defined_Function() :
echo "user defined exception exception\n";