[Tutor] Regarding Exceptions
Alan Gauld
alan.gauld at btinternet.com
Mon Feb 17 16:30:17 CET 2014
On 17/02/14 11:44, Khalid Al-Ghamdi wrote:
> Why is it i can use mu custom class exception without creating an
> exception object first?
There are formatting problems when I try to copy your code.
I've tried to fix them below, apologies if I got it wrong.
However you do create an instance when you raise it...
> class ShortInputException(Exception):
> def __init__(self, length, atleast):
> Exception.__init__(self)
> self.length = length
> self.atleast = atleast
>try:
> text = input()
> if len(text) < 3:
> raise ShortInputException(len(text), 3)
You have your class name followed by parens.
That's how you create an instance.
So you are raising an instance of your class.
except ShortInputException as ex:
print(...
And you catch the instance as ex here...
But remember that in Python classes are objects too...
So you don't always need to create an instance to
use a class.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list