Есть много встроенных классов исключений, таких как EOFError, KeyboardInterrupt и т. Д. Но как я могу создать свой собственный класс исключений. Например, если я хочу сохранить ограничение на то, что пользователь должен ввести строку длиной минимум три.Как я могу получить пользовательское исключение в Python?
0
A
ответ
1
Проверьте этот код для заданного пользователем исключения:
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))
1
Вы можете определить исключение либо с в своем классе, или вы можете создать свой собственный класс исключения в следующем.
/** * Определение класса ваше исключение, которое распространяется исключение */
Класс 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";