There are many inbuilt exception classes like EOFError, KeyboardInterrupt, etc. But how can I make my own exception class. For instance, if I want to keep constraint that user should enter a string of length minimum three.
Asked
Active
Viewed 808 times
2 Answers
1
Check this code for user-defined exception:
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))

dhaval.soni195
- 19
- 3
1
You can define your exception either with in your class or you can create your own exception class in the following .
/** * Define a your exception class which extends Exception */
class Your_Exception extends 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";

Nag
- 17
- 1